1

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?

0

3 Answers 3

2
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)

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

Comments

2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.