Skip to main content

Help newbie

1 reply [Last post]
Joined: 2007-06-23

I'm new to java programming so I was wondering if i can get some help from some of the experts around here.

The problem that I have is about concatenating a string. I have first a class that allows the user to input a anything; length of the word, how many whitespaces between each word and the number of words are all dependable on the user that types it.

So what I was looking for was creating a method; this method would allow the program to in a way compress the inputted words to a single word without any whitespaces.

The user may enter something like this: (\t) never (\t\t\t) Oddor Even (\t\t)
the (\t) is tabs, apparently this forum does not allow free whitespaces to be made

The output I want from the method is of course: neverOddorEven

The method I started is like this but i encountered several problems while compiling the java file.

private static String compressIt(String p)
String concatenated[];
p = p.trim();
p = p.split("[ \t]");
for(int i = 0; i < p.length; i++)
concatenated = p[i] + p[i+1];
return (concatenated);

Please help me modify this program.. Thanks

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2005-09-23


String has a replace method...

String text = "Some Text\tHere";
text = text.replace(" ", "");
text = text.replace("\t", "");

( If you know regex you can also use replaceAll(...) )

These effectively replace the chosen String with an empty String...

Remember that Strings are immutable (they cannot be changed) that is why you have to use text = text.replace(...) and you cannot simply use text.replace(...);

You could also use a third party library such as Apache StringUtils StringUtils.replace("aba", "a", "")

Message was edited by: klopperq

Message was edited by: klopperq