Generally, we use trim() to remove white spaces in a string. Suppose if you have a string content with multiple white spaces between words rather than the intended single space, we have to remove those additional spaces in order to continue using the String for further manipulation.
We have the following ways to achieve this.
1) With the help of StringTokenizer class.
Example code:
package basics;
import java.util.StringTokenizer;
public class StringTokenizing {
public static void main(String a[]){
String str = "My name is Cassian Raja ";
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
}
}
Result:
--------
My name is Cassian Raja
How it works?
StringTokenizer splits the String str using the delimiter as " " (a white space) and stores the splitted words as tokens into st. Loop through each token and add each word into a string buffer object along with a single whitespace to separate each word(token). Finally use trim() to remove the white space at the end of the string and print it.
StringTokenizer is a legacy class and it is being used only for compatibilitypurposes and we have to avoid it in or new code. Instead, we can use String's
split() method to achieve this task.
2. With the help of split() method.
Using split() method will split the string into basic tokens with delimiter as spaces.
Example code:
package basics;
import java.util.StringTokenizer;
public class StringTokenizing {
public static void main(String a[]){
String str = "My name is Cassian Raja ";
String str1[] = str.split("\\s+");
String newString = "";
for(int i=0; i<str1.length; i++){
newString = newString.concat(str1[i] + " ");
}
System.out.println(newString.trim());
}
}
Result:
--------
My name is Cassian Raja
Here, we use the regex pattern "\\s+" to denote multiple white spaces (more than one) as the delimiter to split the words in the string.
No comments:
Post a Comment