Soatl
Soatl

Reputation: 10592

Java: Replace a specific character with a substring in a string at index

I am struggling with how to actually do this. Say I have this string

"This Str1ng i5 fun"

I want to replace the '1' with "One" and the 5 with "Five"

"This StrOneng iFive fun"

I have tried to loop thorough the string and manually replace them, but the count is off. I have also tried to use lists, arrays, stringbuilder, etc. but I cannot get it to work:

char[] stringAsCharArray = inputString.toCharArray();
ArrayList<Character> charArraylist = new ArrayList<Character>();

for(char character: stringAsCharArray) {
    charArraylist.add(character);
}

int counter = startPosition;

while(counter < endPosition) {
    char temp = charArraylist.get(counter);
    String tempString = Character.toString(temp);
    if(Character.isDigit(temp)){
        char[] tempChars = digits.getDigitString(Integer.parseInt(tempString)).toCharArray(); //convert to number

        charArraylist.remove(counter);
        int addCounter = counter;
        for(char character: tempChars) {
            charArraylist.add(addCounter, character);
            addCounter++;
        }

        counter += tempChars.length;
        endPosition += tempChars.length;
    }
    counter++;
}

I feel like there has to be a simple way to replace a single character at a string with a substring, without having to do all this iterating. Am I wrong here?

Upvotes: 1

Views: 1828

Answers (3)

Rishi
Rishi

Reputation: 1183

String[][] arr = {{"1", "one"}, 
                           {"5", "five"}};

String str = "String5";
for(String[] a: arr) {
    str = str.replace(a[0], a[1]);
}

System.out.println(str);

This would help you to replace multiple words with different text.

Alternatively you could use chained replace for doing this, eg :

str.replace(1, "One").replace(5, "five");

Check this much better approach : Java Replacing multiple different substring in a string at once (or in the most efficient way)

Upvotes: 2

Arnav Borborah
Arnav Borborah

Reputation: 11789

Try the below:

string = string.replace("1", "one");
string = string.replace("5", "five");

.replace replaces all occurences of the given string with the specified string, and is quite useful.

Upvotes: 1

Thilo
Thilo

Reputation: 262504

You can do

string = string.replace("1", "one");
  1. Don't use replaceAll, because that replaces based on regular expression matches (so that you have to be careful about special characters in the pattern, not a problem here).

  2. Despite the name, replace also replaces all occurrences.

  3. Since Strings are immutable, be sure to assign the result value somewhere.

Upvotes: 2

Related Questions