-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP3for2017.java
More file actions
91 lines (63 loc) · 1.85 KB
/
P3for2017.java
File metadata and controls
91 lines (63 loc) · 1.85 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
90
91
public class P3for2017 {
public static void main(String[] args){
Phrase phr = new Phrase("A cat ate late.");
phr.replaceNthOccurrence("ct",2, "att");
phr.findLastOccurrence("at");
phr.findNthOccurrence("at", 2);
}
}
class Phrase{
private String currentPhrase;
public Phrase(String p){
currentPhrase = p;
}
public String getCurrentPhrase(){
return getCurrentPhrase();
}
public void replaceNthOccurrence(String str, int n, String repl) {
int index = 0;
for(int i = 0; i < currentPhrase.length(); i++) {
if (!str.equals(currentPhrase.substring(i, i + str.length()))) {
index = -1;
continue;
} else {
index = i;
break;
}
}
if (index != -1) {
currentPhrase = currentPhrase.substring(0, index) + repl + currentPhrase.substring(index + str.length());
}
System.out.println(currentPhrase);
}
public int findLastOccurrence(String str)
{
int n = 1;
int index = -1;
int nextIndex = findNthOccurrence(str, n);
while(nextIndex != -1)
{
index = nextIndex;
n++;
nextIndex = findNthOccurrence(str, n);
System.out.println(index);
}
return index;
}
public int findNthOccurrence(String str, int n) {
int index = 0;
for(int i = 0; i < currentPhrase.length(); i++) {
if (str.equals(currentPhrase.substring(i, i + str.length()))) {
index = -1;
continue;
} else {
index = i;
break;
}
}
if (index == -1){
System.out.println(index);
}
return index;
}
}