Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a char in a string without using Replace() in Java?

I've been having trouble with this assignment:

Given a string, replace the first occurrence of 'a' with "x", the second occurrence of 'a' with "xx" and the third occurrence of 'a' with "xxx". After the third occurrence, begin the replacement pattern over again with "x", "xx", "xxx"...etc.; however, if an 'a' is followed by more than 2 other 'a' characters in a row, then do not replace any more 'a' characters after that 'a'.

No use of the replace method is allowed.

aTo123X("ababba") → "xbxxbbxxx"

aTo123X("anaceeacdabnanbag") → "xnxxceexxxcdxbnxxnbxxxg"

aTo123X("aabaaaavfaajaaj") → "xxxbxxxaaavfaajaaj"

aTo123X("pakaaajaaaamnbaa") → "pxkxxxxxxjxxaaamnbaa"

aTo123X("aaaak") → "xaaak"

My code's output is with a's included, x's added but not the correct amount of x's.


public String aTo123X(String str) {
  /*
  Strategy: 
  get string length of the code, and create a for loop in order to find each individual part of the String chars.check for a values in string and take in pos of the a.
  if one of the characters is a
    replace with 1 x, however, there aren't more than 2 a's immediately following first a and as it keeps searching through the index, add more x's to the original string, but set x value back to 1 when x reaches 3.
    if one of characters isn't a,
    leave as is and continue string.
  */

  String xVal = "";
  String x = "x";
  String output = "";
  for (int i = 0; i < str.length(); i++){

    if( str.charAt(i) == 'a'){
       output += x; 
       str.substring(i+1, str.length());
    }
    output += str.charAt(i);
  }
  return output;
}

1 Answers

This is the code that does the same. I've commented the code to explain what it does

public class ReplaceChar {

    public static void main(String... args){
        String[] input =new String[]{"ababba","anaceeacdabnanbag","aabaaaavfaajaaj"};

        StringBuilder result = new StringBuilder();

        for (int i= 0; i < input.length;i++){
            result.append(getReplacedA(input[i]));
            result.append("\n");
        }

        System.out.println(result);

    }

    private static String getReplacedA(String withA){
        // stringBuilder for result
        StringBuilder replacedString = new StringBuilder();

        // counting the number of time char 'a' occurred in String for replacement before row of 'aaa'
        int charACount = 0;

        // get the first index at which more than two 'aa' occurred in a row
        int firstIndexOfAAA = withA.indexOf("aaa") + 1;

        // if 'aaa' not occurred no need to add the rest substring
        boolean addSubRequired = false;

        // if the index is 0 continue till end
        if (firstIndexOfAAA == 0)
            firstIndexOfAAA = withA.length();
        else
            addSubRequired = true;

        char[] charString = withA.toCharArray();

        //Replace character String[] array
        String[] replace = new String[]{"x","xx","xxx"};

        for(int i = 0; i < firstIndexOfAAA; i++){
                if (charString[i] == 'a'){
                    charACount++;
                charACount = charACount > 3 ? 1 : charACount ;
                // add the number x based on charCount
                replacedString.append(replace[charACount - 1]);
                }else{
                    replacedString.append(charString[i]);
                }
        }

        // if the String 'aaa' has been found previously add the remaining subString
        // after that index
        if (addSubRequired)
            replacedString.append(withA.substring(firstIndexOfAAA));

        // return the result
        return replacedString.toString();
    }

}

Output:

xbxxbbxxx
xnxxceexxxcdxbnxxnbxxxg
xxxbxxxaaavfaajaaj

EDIT : Some Improvement You can make for some corner cases in the getReplacedA() function:

  1. Check if char 'a' is there or not in the String if not just return the String No need to do anything further.

  2. Use IgnoreCase to avoid the uppercase or lowercase possibility.

like image 133
Ankur Anand Avatar answered Mar 27 '26 06:03

Ankur Anand