Spaces:
Running
Running
File size: 2,425 Bytes
803a950 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
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
|