forked from task032015/stringProblem
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRemoveCharacters.java
More file actions
89 lines (67 loc) · 2.21 KB
/
RemoveCharacters.java
File metadata and controls
89 lines (67 loc) · 2.21 KB
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
/* This program removes all occurrences of a specified character from a string
*/
import acm.program.*;
public class DeleteCharacters extends ConsoleProgram {
public void run() {
while (true) {
String str = readLine("Enter a phrase: ");
String getChar = readLine("Enter a letter you want to remove: ");
char ch = getChar.charAt(0);
int indexOfString = str.indexOf(ch);
println(removeAllOccurrences (str, ch));
if (indexOfString == -1) {
println("Error: You did not enter a phrase. Try again!");
}
}
}
// test vishnu
/* Using Iterative approach
private String removeAllOccurrences(String str, char ch) {
String result = "";
for (int i=0; i < str.length(); i++) {
if (str.charAt(i) != ch) {
result = result + str.charAt(i);
}
}
return result;
}
/* Using "Replace" method in String Class
private String removechar(String str, char ch) {
return str.replace(String.valueOf(ch), "");
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class DeleteAllCharTest {
@Test
public void deleteatStart() {
assertEquals("b",DeleteAllCharTest.removeAllOccurrences("eebay", 'e'));
assertEquals("b",DeleteAllCharTest.removechar("ppayal", 'p'));
}
@Test
public void deleteFromMiddle() {
assertEquals("acd",DeleteAllCharTest.deleteCharIter("abcd", 'b'));
assertEquals("acd",DeleteAllCharTest.deleteChar("abcd", 'b'));
}
@Test
public void deleteEnd() {
assertEquals("abc",DeleteAllCharTest.deleteCharIter("ebayyy", 'y'));
assertEquals("abc",DeleteAllCharTest.deleteChar("oracleeee", 'e'));
}
@Test
public void deleteNoExistentChar() {
assertEquals("abc",DeleteAllCharTest.deleteCharIter("abc", 'd'));
assertEquals("abc",DeleteAllCharTest.deleteChar("abc", 'd'));
}
@Test
public void deleteAllChars() {
assertEquals("",DeleteAllCharTest.deleteCharIter("n", 'n'));
assertEquals("",DeleteAllCharTest.deleteChar("z", 'z'));
assertEquals("",DeleteAllCharTest.deleteCharIter("yyyyyyyyyyyy", 'y'));
}
@Test
public void deleteWithSpaces() {
assertEquals("this is a test",DeleteAllCharTest.deleteCharIter("thisX isX aX testX", 'X'));
assertEquals("this is a test",DeleteAllCharTest.deleteChar("thisX isX aX testX", 'X'));
}
}