PDA

View Full Version : Java problem


Hoplite
06-19-2009, 10:26 PM
what is the java equivalent code for the following

char array[5];
printf("enter desired characters: ");

for(i=0;i<5;i++)
scanf("%c",&array[i]);


what i did was i declared a string array, took all the characters (including spaces) in a single string, stored it into the array and removed the spaces...but there has to be a better way, isn't it???

Chriz
06-19-2009, 10:34 PM
Can't you use regular expressions to do that?

Something like:

foo = bar.replace(/\s/g,"");

Tux
06-20-2009, 10:35 AM
You could also do it something like this:

String name = "enter desired characters: ";
int size = name.length();

for (int i = 0; i < size; i++)
{
if (name.charAt(i) <> ' ')
{
System.out.println(name.charAt(i));
}
}

That should work, but it's been quite a while since I've actually done anything in java.