December 23, 2010
Java Replace String Function
Problem
Write a Java method to replace a sub string in a given text with another string of the same size
Solution
Loop through the text character by character. Starting at the current character loop a number of times equal to the size of the sub string while comparing characters in the original text and the sub string that we are looking for. If a match is found replace it with the new string. If the sub string and the new string are not of the same size then it needs special handling but in this question we are assuming they are of the same size
Code
Here is the code in Java
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 |
//Main function public static void main(String[] args) { //Sample text String text = "aaabbbaaaa"; //Text to replace String str = "aaa"; //Replace it with String newstr = "AAA"; //Call function char[] out = Replace( //Pass parameters text.toCharArray(), str.toCharArray(), newstr.toCharArray() ); //Print output System.out.println(out); } //Replace function: //str and newstr are assumed to //have the same length static char[] Replace(char[] text, char[] str, char[] newstr) { //Go through the text character by character //note that i should not go all the way to the end of the //text because we need to take into consideration that //j starts at i then loop a number of times that is equal //to the length of str so we need to take this into account for (int i = 0; i < text.length - str.length + 1; i++) { //We start at i looking for a matching sub string //we initially assume that there is a match however //we change it to false the moment we find the first //none matching character boolean found = true; int k = 0; //Check if the sub string matches for (int j = i; j < text.length && k < str.length; j++, k++) { //If one character is different then no match if (text[j] != str[k]) { found = false; } } //If a matching sub string is found then replace it if (found) { for (k = 0; k < newstr.length; k++) { text[i+k] = newstr[k]; } } } //Return result return text; } |