0

I have a String , String originalString= "This car is my car";
I want to replace "car" with "bike", without using string replace() method.

class StringTest{
   public static void main(String[] args){
      String originalString = "This car is my car";
      String replacedString = replaceMethod(original, "car", "bike");
      System.out.println(replacedString);
   }  
}
static String replaceMethod( String original, String toReplace, String replacedWith){
    // enter code here
    return "";
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
user3114910
  • 19
  • 1
  • 1
  • 2
  • Just use `String.replace`. Or use a Matcher and a regular expression (either direct replacement or rebuild with appendReplacement/appendTail). Or use other one-off `indexOf/substring/split` and build the result manually. I'd stick with `String.replace` unless there is a "good" reason not to. – user2864740 Dec 18 '13 at 11:17

5 Answers5

5

You can split on "car" and then concatenate with adding "bike"

import java.util.*;

class StringTest 
{
    public static void main(String[] args)
    {
        String originalString = "This car is my car";
        String replacedString = replaceMethod(originalString, "car", "bike");
        System.out.println(replacedString);
    }

    static String replaceMethod(String str, String from, String to) 
    {
        String[] arr = str.split(from);
        StringBuilder output = new StringBuilder();

        int i = 0;
        for (; i < arr.length - 1; i++)
        output.append(arr[i]).append(to);

        output.append(arr[i]);
        if (str.substring(str.lastIndexOf(" ")).equalsIgnoreCase(" " + from))
            output.append(to);

        return output.toString();
    }
}

originalString

This car is my car

output

This bike is my bike

Thanks for Mr. Polywhirl for his help.

Ahmed Hamdy
  • 2,547
  • 1
  • 17
  • 23
2

try this

static String replaceMethod(String original, String toReplace,
        String replacedWith) {
    for(;;) {
        int i = original.indexOf(toReplace);
        if (i == -1) {
            break;
        }
        original = original.substring(0, i) + replacedWith + original.substring(i + toReplace.length());
    }
    return original;
}

or better yet simply copypaste Apache's StringUtils method

public static String replace(String text, String searchString, String replacement, int max) {
    if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
        return text;
    }
    int start = 0;
    int end = text.indexOf(searchString, start);
    if (end == INDEX_NOT_FOUND) {
        return text;
    }
    int replLength = searchString.length();
    int increase = replacement.length() - replLength;
    increase = increase < 0 ? 0 : increase;
    increase *= max < 0 ? 16 : max > 64 ? 64 : max;
    StringBuilder buf = new StringBuilder(text.length() + increase);
    while (end != INDEX_NOT_FOUND) {
        buf.append(text.substring(start, end)).append(replacement);
        start = end + replLength;
        if (--max == 0) {
            break;
        }
        end = text.indexOf(searchString, start);
    }
    buf.append(text.substring(start));
    return buf.toString();
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

Assuming that this is homework and you are looking for an algorithm (which is why you aren't using String.replace), just remember that strings and arrays are basically identical and can both be iterated.

A simple (inefficient) algorithm:

1.Create a submethod to match a substring against the current index in the main string. i.e.

private boolean matchAt(String inputString, String target, int index){
    // YOUR CODE HERE - returns 'true' if the target string occurs in the 
    // inputString at the specified index.
}

2.Iterate over the input string, testing at each letter if the target word has been found.

3.Append output one character at a time to a StringBuilder, based on whether or not the target word has been found.

For a more efficient algorithm, check out the following link on how string search can be implemented using suffix matching: http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm

Alex
  • 18,332
  • 10
  • 49
  • 53
0

this is not a good method but we can also do like this

 public static void main(String[] args) {
      String org= "This car is my car";
      String [] temp=org.split(" ");
      int len=temp.length;
      String ne = "";
      for(int i=0;i<len;i++)
      {
          if(temp[i].matches("car"))
              temp[i]="bike";
          ne=ne+temp[i]+" ";

      }
        System.out.println(ne);
    }
Lijo
  • 6,498
  • 5
  • 49
  • 60
0

Another alternative...

import java.util.*;

class Replace {
    public static void main (String[] args) {
        String originalString = "This car is my car";
        String replacedString = replaceMe(originalString, "car", "bike");
        System.out.println(replacedString);
    }

    public static String replaceMe(String str, String from, String to) {
        String[] arr = str.split(" ");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equals(from)) {
                arr[i] = to;
            }
        }
        return join(arr, " ");
    }

    public static String join(String[] arr, String delim) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append(arr[i]);

            if (i < arr.length - 1)
                sb.append(delim);
        }
        return sb.toString();
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132