0

I have a String "speed,7,red,fast". I want to replace the 7 by a String "Seven". How do I do that ?

More details -

7 can be replaced by ANY string and not just "Seven". It could also be "SevenIsHeaven". I don't want to replace all occurrences of 7. Only 7 at the specified index, ie use the index of 7 to replace 7 by some string.

david blaine
  • 5,683
  • 12
  • 46
  • 55

4 Answers4

7
 replaceAll("7", "Seven") //simple as that

EDIT

Then you should look for the specified index.

 String input = "test 7 speed,7,red,fast yup 7 tr";
    int indexInteresdIn = 13;
    if(input.charAt(indexInteresdIn) == '7'){
        StringBuilder builder = new StringBuilder(input);
        builder.replace(indexInteresdIn, indexInteresdIn+1, "Seven");
        System.out.println(builder.toString());
    }
Eugene
  • 117,005
  • 15
  • 201
  • 306
4

Because String is immutable you should use StringBuilder for better performance.

http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

yourStringBuiler.replace(
                   yourStringBuiler.indexOf(oldString),
                   yourStringBuiler.indexOf(oldString) + oldString.length(),
                   newString);`

If you want to replace a whole String like the String.replaceAll() does you could create an own function like this:

public static void replaceAll(StringBuilder builder, String from, String to)
{
    int index = builder.indexOf(from);
    while (index != -1)
    {
        builder.replace(index, index + from.length(), to);
        index += to.length(); // Move to the end of the replacement
        index = builder.indexOf(from, index);
    }
}

Source: Replace all occurrences of a String using StringBuilder?

However if you doesn't need it frequently and performance is not that important a simple String.replaceAll() will do the trick, too.

Community
  • 1
  • 1
das Keks
  • 3,723
  • 5
  • 35
  • 57
2

How about simply like below ?

 String str =  "speed,7,red,fast";
str = str.replace("7", "Seven");

7 can be replaced by ANY string and not just "Seven". It could also be "SevenIsHeaven". I don't want to replace all occurrences of 7. Only 7 at the specified index.

Or if you wanna use regex to replace the first numeric to a meaningful String.

 String str =  "speed,7,red,fast";
str = str.replaceFirst("\\d", "Seven");
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

better way is to store the string itself in an array, spiting it at a space.

String s[];
static int index; 
s = in.readLine().spilt(" ");

Now scan the array for the specified word, at the specified index and replace that with the String you desire.

for(int i =0;i<s.length; i++)
{
 if((s[i] == "7")&&(i==index))
{
  s[i]= "Seven";
}
}