2015-10-28 3 views
3

У меня возникли проблемы с этим заданием:Как заменить символ в строке без использования Replace() в Java?

Учитывая строку, заменить первое вхождение «в» с «х», вторым вхождением «A» с «хм» и третьим появления «a» с «xxx». После третьего появления снова запустите шаблон замены «x», «xx», «xxx» ... и т. Д .; однако, если за «a» следуют более двух других символов «a» в строке, то вместо этого «a» не заменяйте символы «a».

Не допускается использование метода замены.

aTo123X ("ababba") → "xbxxbbxxx"

aTo123X ("anaceeacdabnanbag") → "xnxxceexxxcdxbnxxnbxxxg"

aTo123X ("aabaaaavfaajaaj") → "xxxbxxxaaavfaajaaj"

aTo123X ("pakaaajaaaamnbaa ") → "pxkxxxxxxjxxaaamnbaa"

aTo123X (" aaaak ") → "xaaak"

Выход моего кода с включенным, добавлено x, но не правильное количество x.


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

И в чем проблема? – Maroun

+0

@MarounMaroun, когда я возвращаю его, он не удаляет a и просто добавляет x, и слишком много в этом отношении –

+1

@Shivam Здесь «a», после которого не должно происходить никаких изменений, является 1-й «a» 1-го появление «aaa». Просто прочитайте свой комментарий только один раз более тщательно, и вы поймете. –

ответ

3

Это код, который делает то же самое. Я прокомментировал код, чтобы объяснить, что он делает

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 

EDIT: Некоторые улучшения можно сделать для некоторых угловых случаев в getReplacedA() функция:

  1. Проверьте, нет ли символа 'a' в String или нет, если вы не просто вернете строку. Не нужно ничего делать.

  2. Используйте IgnoreCase, чтобы избежать заглавной или строчной буквы.

+0

Это отличное решение, однако у меня было больше выходных данных, которые не работали должным образом, я добавил их на вопрос –

+1

Поскольку ваш Заявление о проблемах говорит более двух других «а» символов в строке сейчас. просто замените 'int firstIndexOfAAA = withA.indexOf (" aaa ") + 1;' строка с int 'firstIndexOfAAA = withA.indexOf (" aaaa ") + 1;' т.е. теперь мы проверяем более 2 символов, т. е. не менее 3 в ряд . Он будет работать в обычном режиме –

+1

Здесь рабочая демонстрация вы можете увидеть https://ideone.com/8Helir –

1

Во-первых, строка неизменна, поэтому ниже утверждение не делает ничего

str.substring(i+1, str.length()); 

Я думаю, вы хотели сделать:

str = str.substring(i+1, str.length()); 

Однако, даже после того, как исправить это, ваша программа все еще не работает. Я не могу понять ваше решение. 1) вы не обнаруживаете больше 3 а в строке. 2) вы не добавляя «хх» или «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; 
} 
0

Я отредактировал мой ответ. Это дает правильное решение:

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; 
} 
+0

Редактировать Этот ответ соответствует требованиям к запросу OP .. Не правильный вывод и логика –

1
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; 
    } 
} 
0

Я использую Map Для хранения, где заменить

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; 
    } 
+0

Я добавил новые выходы, которые не применимы к вашему коду –

1

я указываю проблемы в коде в виде комментариев в самом коде.

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; 
} 
Смежные вопросы