如何在Java中不使用replace()替换字符串中的字符?

如何在Java中不使用replace()替换字符串中的字符?,java,regex,string,char,Java,Regex,String,Char,我在这项任务中遇到了问题: 给定一个字符串,将第一次出现的“a”替换为“x”,第二次出现的“a”替换为“xx”,第三次出现的“a”替换为“xxx”。第三次出现后,用“x”、“xx”、“xxx”等重新开始替换模式。;但是,如果一行中“a”后面跟有两个以上的其他“a”字符,则不要在“a”之后再替换任何“a”字符 不允许使用替换方法 aTo123X(“ABABA”)→ “xbxxbbxxx” aTo123X(“anaceeAcadbanbag”)→ “xnxxexxxcdxbnxxnbxxxg” aT

我在这项任务中遇到了问题:

给定一个字符串,将第一次出现的“a”替换为“x”,第二次出现的“a”替换为“xx”,第三次出现的“a”替换为“xxx”。第三次出现后,用“x”、“xx”、“xxx”等重新开始替换模式。;但是,如果一行中“a”后面跟有两个以上的其他“a”字符,则不要在“a”之后再替换任何“a”字符

不允许使用替换方法

aTo123X(“ABABA”)→ “xbxxbbxxx”

aTo123X(“anaceeAcadbanbag”)→ “xnxxexxxcdxbnxxnbxxxg”

aTo123X(“aabaaavfaajaaj”)→ “xxxxxxaaavfaajaaj”

aTo123X(“Pakaaaaamnbaa”)→ “pxkxxxxxxjxxaaamnbaa”

aTo123X(“aaaak”)→ “沙克”

我的代码的输出中包含了a,添加了x,但数量不正确


公共字符串aTo123X(字符串str){
/*
战略:
获取代码的字符串长度,并创建一个for循环,以便找到字符串字符的每个单独部分。检查字符串中的a值并取a的pos。
如果其中一个字符是
替换为1 x,但是,紧跟在第一个a之后的a不超过2个,并且随着它不断搜索索引,在原始字符串中添加更多的x,但是当x达到3时,将x值设置回1。
如果其中一个角色不是,
保持原样并继续字符串。
*/
字符串xVal=”“;
字符串x=“x”;
字符串输出=”;
对于(int i=0;i
首先,字符串是不可变的,所以下面的语句什么也不做

str.substring(i+1, str.length());
我猜你想做:

str = str.substring(i+1, str.length());
但是,即使修复了这个问题,您的程序仍然无法工作。我真的不能理解你的解决办法。1) 连续检测到的a数不超过3个。2) 您根本没有添加“xx”或“xxx”

这是我的版本,到目前为止对我有效:

public static void main(String[] args) {
    System.out.println(aTo123X("ababba")); // "xbxxbbxxx"

    System.out.println(aTo123X("anaceeacdabnanbag")); // "xnxxceexxxcdxbnxxnbxxxg"

    System.out.println(aTo123X("aabaaaavfaajaaj")); // "xxxbxxxaaavfaajaaj"
}

public static String aTo123X(String str) {
    String output = "";
    int aOccurrence = 0;
    String[] xs = {"x", "xx", "xxx"};
    for (int i = 0; i < str.length(); ++i) {
        if (str.charAt(i) == 'a') {
            output += xs[aOccurrence % 3]; // append the x's depending on the number of a's we have seen, modulus 3 so that it forms a cycle of 3
            if (i < str.length() - 3 && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 'a' && str.charAt(i + 3) == 'a') {//if an 'a' is followed by more than 2 other 'a' characters in a row
                output += str.substring(i + 1);
                break;
            } else {
                ++aOccurrence; // increment the a's we have encountered so far
            }
        } else {
            output += str.charAt(i); // append the character if it is not a
        }
    }
    return output;
}
publicstaticvoidmain(字符串[]args){
System.out.println(aTo123X(“ababa”);/“xbxxbbxxx”
System.out.println(aTo123X(“anaceeacdbanbag”);/“xnxceexxxxcdxbnxxnbxxxg”
System.out.println(aTo123X(“aabaaavfaajaaj”);/“xxxxxxaaavfaajaaj”
}
公共静态字符串aTo123X(字符串str){
字符串输出=”;
int A发生率=0;
字符串[]xs={“x”,“xx”,“xxx”};
对于(int i=0;i
我已经编辑了我的答案。这一个给出了正确的解决方案:

public static void main (String[] args) throws InterruptedException, IOException, JSONException {
    System.out.println(aTo123X("ababba")); //xbxxbbxxx

    System.out.println(aTo123X("anaceeacdabnanbag")); //xnxxceexxxcdxbnxxnbxxxg

    System.out.println(aTo123X("aabaaaavfaajaaj")); //xxxbxxxaaavfaajaaj
}

public static String aTo123X(String str) {
    String x = "x";
    String xx = "xx";
    String xxx = "xxx";
    int a = 1;
    int brek = 0;

    String output = "";
    for (int i = 0; i < str.length(); i++) {
        if(str.charAt(i) == 'a' && a == 1) {
            output += x; 
            str.substring(i+1, str.length());
            a = 2;
            try {
                if(str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a')
                    brek += 1;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else if(str.charAt(i) == 'a' && a == 2) {
            output += xx; 
            str.substring(i+1, str.length());
            a = 3;
            try {
                if(str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a')
                    brek += 1;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else if(str.charAt(i) == 'a' && a == 3) {
            output += xxx; 
            str.substring(i+1, str.length());
            a = 1;

            try {
                if(str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a')
                    brek += 1;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else {
            output += str.charAt(i);
            brek = 0;
        }
        if(brek>0) {
            output += str.substring(i+1);
            break;
        }
    }
    return output;
}
publicstaticvoidmain(String[]args)抛出InterruptedException、IOException、JSONException{
System.out.println(aTo123X(“ababa”);//xbxxbbxxx
System.out.println(aTo123X(“anaceeacdbanbag”);//xnxceexxxxcdxbnxxnbxxxg
System.out.println(aTo123X(“aabaaavfaajaaj”);//xxxxxxaaavfaajaaj
}
公共静态字符串aTo123X(字符串str){
字符串x=“x”;
字符串xx=“xx”;
字符串xxx=“xxx”;
INTA=1;
int-brek=0;
字符串输出=”;
对于(int i=0;i0){
输出+=str.substring(i+1);
打破
}
}
返回输出;
}

这是执行相同操作的代码。我已经对代码进行了注释,解释了它的功能

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();
    }

}
编辑:在getReplacedA()函数中,您可以对某些转角情况进行一些改进:

  • 检查字符串中是否有字符“a”,如果没有,只返回字符串,无需进一步操作

  • 使用IgnoreCase避免大写或小写的可能性

  • 公共类NewClass{
    公共静态void main(字符串[]args){
    System.out.println(aTo123X(“ababa”);/“xbxxbbxxx”
    System.out.println(aTo123X(“anaceeacdbanbag”);/“xnxceexxxxcdxbnxxnbxxxg”
    System.out.println(aTo123X(“aabaaavfaajaaj”);//xxxbxxxaaavfaaja
    
    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();
        }
    
    }
    
    xbxxbbxxx
    xnxxceexxxcdxbnxxnbxxxg
    xxxbxxxaaavfaajaaj
    
    public class NewClass {
    
        public static void main(String[] args) {
            System.out.println(aTo123X("ababba")); // "xbxxbbxxx"
            System.out.println(aTo123X("anaceeacdabnanbag")); // "xnxxceexxxcdxbnxxnbxxxg"
            System.out.println(aTo123X("aabaaaavfaajaaj")); //xxxbxxxaaavfaajaaj
        }
    
        public static String aTo123X(String str) {
            String output = "";
            int aCount = 0;
            int inRow = 0;
            for (int i = 0; i < str.length();) {
                if (str.charAt(i) == 'a') {
                    if (inRow <= 1) {
                        inRow++;
                        aCount++;
    
                        if (aCount == 1) {
                            output += "x";
                        } else if (aCount == 2) {
                            output += "xx";
                        } else {
                            output += "xxx";
                            aCount = 0;
                        }
    
                        boolean multiple = ((i + 1) < str.length()) && (str.charAt(i + 1) == 'a')
                                && ((i + 2) < str.length()) && (str.charAt(i + 2) == 'a');
    
                        if (multiple) {
                            i++;
                            while (i < str.length()) {
                                output += str.charAt(i++);
                            }
                            return output;
                        }
                    } else {
                        output += str.charAt(i);
                    }
                } else {
                    output += str.charAt(i);
                    inRow = 0;
                }
                i++;
            }
            return output;
        }
    }
    
        public static void main(String[] args) {
            System.out.println(aTo123X("ababba"));//xbxxbbxxx
            System.out.println(aTo123X("anaceeacdabnanbag"));//xnxxceexxxcdxbnxxnbxxxg
            System.out.println(aTo123X("aabaaaavfaajaaj"));//xxxbxxxaaavfaajaaj
        }
    
        public static String aTo123X(String str){
            String res = "";
            int nthReplace = 1; //Integer to store the nth occurence to replace
            //Map to store [key == position of 'a' to replace]
            //[value == x or xx or xxx]
            Map<Integer, String> toReplacePos = new HashMap<>();
            //The loop to know which 'a' to replace
            for (int i = 0; i < str.length(); i++) {
                if(str.charAt(i) == 'a'){
                    toReplacePos.put(i, nthReplace % 3 == 1 ? "x": (nthReplace % 3 == 2 ? "xx": "xxx"));
                    nthReplace++;
                    //Break if an 'a' is followed by more than 2 other 'a'
                    try {
                        if((str.charAt(i+1) == 'a') 
                           && (str.charAt(i+2) == 'a') 
                           && (str.charAt(i+3) == 'a')){
                            break;                        
                        }                    
                    } catch (StringIndexOutOfBoundsException e) {
                    }
                } 
            }
            //Do the replace
            for (int i = 0; i < str.length(); i++) {
                res += toReplacePos.containsKey(i) ? toReplacePos.get(i) : str.charAt(i);                 
            }
            return res;
        }
    
    public String aTo123X(String str) {
        //You are not using xVal variable in your code, hence it's obsolete
        String xVal = "";
        //You don't need x variable as you can simply use string concatenation
        String x = "x";
        String output = "";
    
        for (int i = 0; i < str.length(); i++) {
    
            /**
             * Here, in "if" block you have not implmented any logic to replace the 2nd and
             * 3rd occurence of 'a' with 'xx' and 'xxx' respectively. Also, substring() returns
             * the sub-string of a string but you are not accepting that string anywhere, and 
             * you need not even use sub-string as "for" loop will cycle through all the
             * characters in the string. If use sub-string method you code will only process
             * alternative characters.
             */
             if( str.charAt(i) == 'a') {
                 output += x; 
                 str.substring(i+1, str.length());
             }
    
             /**
              * Because of this statement a's are also returned, because this statement gets 
              * in both scenarios, whether the current character of string is a or not.
              * But, this statement should get executed only when current character of the
              * string is 'a'. So, in terms of coding this statement gets executed no matter
              * "if" loop is executed or not, but it should get executed only when "if" loop
              * is not executed. So, place this statement in else block.
              */
              output += str.charAt(i);
        }
        return output;
    }
    
    public String aTo123X(String str) {
        String output = "";
        int count = 1;
        boolean flag = true;
    
        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == 'a' && flag == true) {
                switch(count) {
                    case 1: output += "x";
                            count++;
                            break;
    
                    case 2: output += "xx";
                            count++;
                            break;
    
                    case 3: output += "xxx";
                            count = 1;
                            break;
                }
    
                if ((str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a') == true) {
                    flag = false;
                }
            }
            else {
                output += str.charAt(i);    
            }
        }
    
        return output;
    }