KaiquanMah's picture
Create 21. Clean up string
803a950 verified
raw
history blame
2.43 kB
Write the method
String clean(String wprd)
which returns a string with "all characters except upper and lower case letters and spaces" stripped from the string given as a parameter.
Example method call:
public static void main(String[] args){
String test = "Hel1234!&%lo";
String cleaned = clean(test);
System.out.println(cleaned);
}
Program outputs:
Hello
import java.util.Random;
public class Test{
public static void main(String[] args){
final Random r = new Random();
String[] words = {
"a.b.c.",
"m1213i342x&#/¤(9985e4456d463?",
"a1b2c3d4e5f6g7h8i9j10",
"!he\"#re¤% &/in() t,.,-he.- m&(#)iddle*^** of&% tr&&ash& is¤ %%a% mes%#%sage"
};
for (String w : words) {
System.out.println("Test with parameter " + w);
System.out.println("Cleaned: " + clean(w));
System.out.println("");
}
}
}
//ADD
// public static String clean(String wprd) {
// String finalWord = "";
// for (char character: wprd) {
// // uppercase
// if (character >= 'A' && character <= 'Z') {
// finalWord+=character;
// }
// //lowercase
// else if (character >= 'a' && character <= 'z') {
// finalWord+=character;
// }
// //spaces
// else if (character == ' ') {
// finalWord+=character;
// }
// }
// return finalWord;
// }
//ADD
public static String clean(String wprd) {
String finalWord = "";
for (int i = 0; i < wprd.length(); i++) {
char character = wprd.charAt(i);
// uppercase
if (character >= 'A' && character <= 'Z') {
finalWord += character;
}
// lowercase
else if (character >= 'a' && character <= 'z') {
finalWord += character;
}
// space
else if (character == ' ') {
finalWord += character;
}
}
return finalWord;
}
}
Test with parameter a.b.c.
Cleaned: abc
Test with parameter m1213i342x&#/¤(9985e4456d463?
Cleaned: mixed
Test with parameter a1b2c3d4e5f6g7h8i9j10
Cleaned: abcdefghij
Test with parameter !he"#re¤% &/in() t,.,-he.- m&(#)iddle*^** of&% tr&&ash& is¤ %%a% mes%#%sage
Cleaned: here in the middle of trash is a message