-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReplaceWord.java
More file actions
80 lines (78 loc) · 2.85 KB
/
Copy pathReplaceWord.java
File metadata and controls
80 lines (78 loc) · 2.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
import java.util.Scanner;
public class ReplaceWord {
static String mostFrequent(String str){
String word;
int prevCount=0,nexCount=0;String frequent = new String();
String[] arr = str.split(" ");
for(int i=0;i< arr.length;i++){
word = arr[i];
for(int j=0;j<arr.length;j++){
if(word.equalsIgnoreCase(arr[j])){
nexCount++;
}
else if( word.length()>arr[i].length() && word.equalsIgnoreCase(arr[i].substring(0,arr[i].length()-1))){
nexCount++;
}
}
if(prevCount<nexCount) {
prevCount = nexCount;
frequent=word;
}
nexCount=0;
}
return frequent;
}
static String leastFrequent(String str){
String word;
int prevCount=0,nexCount=0;String frequent = new String();
String[] arr = str.split(" ");
for(int i=0;i< arr.length;i++){
word = arr[i];
for(int j=0;j<arr.length;j++){
if(word.equalsIgnoreCase(arr[j])){
nexCount++;
}
else if( word.length()>arr[i].length() && word.equalsIgnoreCase(arr[i].substring(0,arr[i].length()-1))){
nexCount++;
}
}
if(prevCount>nexCount) {
prevCount = nexCount;
frequent=word;
}
nexCount=0;
}
return frequent;
}
static String changes(String str,String replace,String replaceWith){
StringBuilder str1= new StringBuilder();
String[] arr = str.split(" ");
for(int i=0;i<arr.length;i++){
String str2=arr[i];
if(str2.equalsIgnoreCase(replaceWith) ){
arr[i]=replace;
}
else if( str2.length()>replaceWith.length() && replaceWith.equalsIgnoreCase(str2.substring(0,str2.length()-1))){
arr[i]=replace+arr[i].charAt(str2.length()-1);
}
str1.append(arr[i]);
str1.append(" ");
}
str = new String(str1);
return str;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Passage : ");
String passage = sc.nextLine();
System.out.println("Enter the Replace word :");
String replace = sc.next();
System.out.println("Enter the that you want to replace with :");
String replaceWith = sc.next();
System.out.println(passage);
String str = changes(passage,replace,replaceWith);
System.out.println(str);
System.out.println(mostFrequent(str));
System.out.println(leastFrequent(str));
}
}