Sri
Sri

Reputation: 21

How to replace an old string with new string for first occurence without using any API

I have string like

String str = "This is john";

In that above string i need replace "is" with "was"

This is my code

class replaces
{
    public static void main(String[] args) 

      {
        String s = "  This is john  ";

        String input = "is";

        String old = "was";

        String s1[] = s.split(" ");

         for(int i=0;i<s1.length;i++)
        {
            if(s1[i]==input)
            {
                s1[i]=old;
            }
        }
        for(int i=0;i<s1.length;i++)
        {
            System.out.println(s1[i]);
        }
}

}

when i execute this its printing the same string -

This is john

If anybody can explain how to solve this if you have that code just post it.

Its useful for me.. Thank You

Upvotes: 0

Views: 55

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

First, let's solve with any reasonable API:

String source = "This is john";
String find = "is";
String replace = "was";

int index = source.indexOf(find);

// actually we don't have to change the first occurense (that is in the "thIS"),
// we want "is" to be a separate word i.e. either in the begining/ending of the string 
// or started/followed by spaces
while (index >= 0) 
  if (((index == 0) || 
       (source.charAt(index - 1) == ' ')) &&
      ((index + find.length() >= source.length()) || 
       (source.charAt(index + find.length()) == ' ')))
    break; // this occurence is OK 
  else
    index = source.indexOf(find, index + 1); // next one, please

String result = index >= 0
    ? source.substring(0, index) + replace + source.substring(index + find.length())
    : source;

then inspect which API used is allowed. I guess, that length(), charAt() have to be allowed; as for indexOf() and substring() you can easily implement them.

Upvotes: 0

Phil
Phil

Reputation: 29

s = s.replace(" is ", " was ");

String method

Upvotes: 0

craigsparks
craigsparks

Reputation: 134

Assuming its Java code, your problem is that in your case, you need to use the equals() method comparison of strings, not the equality sign. Rather use s1[i].equals(input) instead of s1[i]==input

Upvotes: 1

Related Questions