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 "";
}
1
  • 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. Commented Dec 18, 2013 at 11:17

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

9 Comments

It's split, not splite.
Thanks @Mr. Polywhirl, I was just going to update it.
I just validated it twice, I updated the post with the output too
Oh, I see. It works by bad input coincidence. Try it with: "This car is my car and I love it"
Does not work for "This car is my car, dude." It prints "This bike is my bike, dude.bike"
|
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();
}

1 Comment

I would use StringBuilder for this. Too much concatenation...
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

Comments

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);
    }

Comments

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();
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.