Example:
String str1 = "Lyubomir";
System.out.println(str1.replace("Ly", "fiko"));
Result: fikoubomir
The method will be implemented using arrays or characters, although Strings can be used as well. This will be much simple, but the idea here is to get more details in how the algorithm works.
On the first pass we have to calculate how many times the string which will be replaced occurs in the input string.
private static int countNumFimesOneStrInOther(char[] str1Arr,char[] str2Arr )
{
//count how many times the second string is in the first one
int counter=0;
for(int i=0; ilength
int j=i;
int k=0;
while(jlength
&& k
{
j++;
k++;
}
//the whole string 2 is in string one
if(k==str2Arr.length)
{
counter++;
}
}
return counter;
}
This will give the size of the resulting character array - the size of the string - number of times the second string occurs*it's length + number of times the second string occurs * it's length:
char[] strResult = new char[str1Arr.length + Math.abs(numTimes*(str3Arr.length-str2Arr.length))];
Here is the full source code of the program:
import java.io.Console;
import java.util.*;
import java.io.*;
import java.lang.*;
//replace all the strings with string
public class StringReplace {public static void main(String[] args)
{
String str1 = args[0];
String str2 = args[1];
String str3 = args[2];
}
{
//count how many times the second string is in the first one
int counter=0;for(int i=0; i
; i++) {
int j=i;
int k=0;
while(j
&& k
j++;
k++;
}
//the whole string 2 is in string one
if(k==str2Arr.length){
counter++;
}
}
return counter;
}
{
if(str1==null || str2==null)
return "";
char[] str2Arr = str2.toCharArray();
char[] str3Arr = str3.toCharArray();
//the result string will be with length x times the number of times the string which replaces the first one occurs
char[] strResult = new char[str1Arr.length + Math.abs(numTimes*(str3Arr.length-str2Arr.length))];for(int i=0; i
; i++) {
int j=i;
int k=0;
&& k
j++;
k++;
}
//the whole string 2 is in string one
if(k==str2Arr.length){
k=0;
while(k
) {
strResult[resIndex] = str3Arr[k];
resIndex++;
k++;
i++;
}
}
resIndex++;
}
}
Better solution will be to use suffix tree or suffix array data structure - which gives the index on the substring in linear time and uses no extra space.