Suppose you have a String str="hello my na me i s John". How will you remove the spaces between words.Its a very basic question asked in interview for freshers.
I have mentioned two ways to do the same problem one is using split function and another is using replace function.
Sample Program:-
/**
*
*/
/**
* @author Dixit
*
*/
public class RemoveSpaceInStrings {
/**
* @param args
*/
public static void main(String[] args) {
String str="hello my na me i s John";
removeSpaceWithSplitFunction(str);
removeSpcaseWithoutSplitFunction(str);
}
private static void removeSpcaseWithoutSplitFunction(String str) {
System.out.println("removeSpcaseWithoutSplitFunction:Resulting String is:-" +str.replace(" ", ""));
}
private static void removeSpaceWithSplitFunction(String str) {
String result = "";
String strArray[] = str.split(" ");
for (int i = 0; i < strArray.length; i++) {
result = result + strArray[i];
}
System.out.println("removeSpaceWithSplitFunction:Resulting String is:-" + result);
}
}
Output
removeSpaceWithSplitFunction:Resulting String is:-hellomynameisJohn
removeSpcaseWithoutSplitFunction:Resulting String is:-hellomynameisJohn
Enjoy Programming :)
No comments:
Post a Comment