Removing spaces in String ArrayList
Hi,
Id like to know how to remove multiple spaces in each String and to allow only one space between each, in an ArrayList.
For example if I had three String variables shown below.
(THE UNDERLINE BETWEEN EACH NUMBER ARE SUPPOSE TO BE SPACES)
String line1 = "_one____two_________three";
String line2 = " ______one___two______three";
String line3= "_one__two________three";
And then to format each String element in the list to allow only one space each?. Shown below
Envisioned Solution.
Line 1: "one two three";
Line 2: "one two three";
Line 3: "one two three";
Thanks
Re: Removing spaces in String ArrayList
Look at the String class's replace... methods. I think the one that uses a regular expression will do what you want.
The leading and trailing spaces can be trimmed.
Re: Removing spaces in String ArrayList
Ive tried using the replaceAll method but it doesn't seem to work at all.
Plus how can you replace spaces with one space if the multiple spaces are arbitrary? What would the reg exp will be?
Re: Removing spaces in String ArrayList
Try this for a regexp: \\s+
Re: Removing spaces in String ArrayList
Yea that seems like the right solution, but it it still results the same.
Here is the sample code below:
Code:
public static void main(String args [])
{
String line1 = " one two three";
System.out.println("Old: "+line1);
line1.replaceAll("\\s+", " ");
System.out.println("New: "+line1);
}
The old and new output are still the same?
Re: Removing spaces in String ArrayList
Please post the results. Be sure to include it in code tags to preserve the spaces.
Quote:
The old and new output are still the same?
You are comparing the old with the old.
Remember that Strings are immutable. You can not change the contents of a String. Look at the method you are using.
Re: Removing spaces in String ArrayList
Thanks. Yea I see where I went wrong.
Thanks again