Question - 1 : Write a java program to find a particular string in another string and replace all occurrences of it with another string.
Constraints :
(a) Time complexity should be O(n)
(b) Should not use replace() or any other such function which directly solve the problem.
Constraints :
(a) Time complexity should be O(n)
(b) Should not use replace() or any other such function which directly solve the problem.
public class FindRep {
public static void main(String[] args) {
new FindRep().findRepStr("We go in a field, but we don't go deep in it and wish to go in another field", "in", "out");
new FindRep().findRepStr("A quick over brown fox over jumped over the over lazy dog over over over", "over", "z");
}
public void findRepStr(String str, String findStr, String repStr) {
String s1 = "", s2 = "", s3 = "";
int index = 0;
while (index != -1) {
if ((index = str.indexOf(findStr)) != -1) {
s1 = str.substring(0, index); //Substring before of findString
s2 = str.substring(index, str.length()).substring(findStr.length(), str.length() - s1.length()); //Substring after of findString
str = s1 + repStr + s2;
}
}
System.out.println(str);
}
}
No comments:
Post a Comment