2014-12-07 66 views
0

我不允許使用replace()。我只能使用substring和indexOf和length()。我如何使用這些方法替換字符?這是我試過的,但它不起作用。如何用另一個字符替換字符而不使用replace()

public static String replace(String s) 
{ 
    int b = 0; 
    String result = ""; 
    int index = s.indexOf(' '); 

    while(index != -1) 
    { 
    result += s.substring(b,index) + '\n'; 
    s = s.substring(index+1); 
    index = s.indexOf(' '); 
    } 

    return result; 
} 

***更正:我拿出b = index;,因爲我意識到這是一個錯誤。現在它唯一的問題是字符串的最後一個字符沒有顯示出來,因爲'str.indexOf('');是-1不符合循環的條件。

+0

你想做什麼?用'\ n''替換''''? – 5gon12eder 2014-12-07 22:05:45

+0

是的。一個新行字符的空間 – PTheCoolGuy 2014-12-07 22:06:24

+0

這是一種奇怪的家庭作業嗎?目的是什麼?你打算從中學習什麼? – 2014-12-07 22:06:59

回答

0

您需要將以前的index存儲在b中。此外,您可以使用indexOf()的第二個參數來控制String中的位置。像,

public static String replace(String s) { 
    int b = 0; 
    String result = ""; 
    int index = s.indexOf(' '); 
    if (index > -1) { 
     while (index != -1) { 
      result += s.substring(b, index) + '\n'; 
      // s = s.substring(index + 1); 
      b = index; 
      index = s.indexOf(' ', index + 1); 
     } 
     result += s.substring(b + 1); 
    } else { 
     result = s; 
    } 
    return result; 
} 
0

你可以做到這一點沒有indexOf和substring。
該實現取自java.lang.String.replace()。

public static String replace(String str, char oldChar, char newChar) { 
    if (oldChar != newChar) { 
     char[] value = str.toCharArray(); 
     int len = value.length; 
     int i = -1; 
     char[] val = value; 

     while (++i < len) { 
      if (val[i] == oldChar) { 
       break; 
      } 
     } 
     if (i < len) { 
      char buf[] = new char[len]; 
      for (int j = 0; j < i; j++) { 
       buf[j] = val[j]; 
      } 
      while (i < len) { 
       char c = val[i]; 
       buf[i] = (c == oldChar) ? newChar : c; 
       i++; 
      } 
      return new String(buf); 
     } 
    } 
    return str; 
} 
0

你可以這樣做,除非你必須使用你提到的所有方法。無論如何,可能都是值得思考的問題。

public static String replace(String s) { 
    String[] split = s.split(""); 
    String result = ""; 
    for (int i = 0; i < split.length; i++) { 
     if (split[i].equals(" ")) { 
     split[i] = "\n"; 
     } 
     result+=split[i]; 
    } 


    return result; 
    } 
0

您還可以通過使用遞歸方法解決任務:

public static void main(String[] args) { 
    System.out.println(replace("a b c ...")); 
} 

public static String replace(final String str) { 
    final int index = str.indexOf(' '); // find the first occurence 
    if (index == - 1) { // if there are no whitespaces ... 
     return str; // ... then return the unchanged String 
    } 
    // cut off the part before the whitespace, append \n to it and then append 
    // the result of another "replace" call with the part after the found whitespace 
    return String.format("%s%s%s", 
     str.substring(0, index), "\n", replace(str.substring(index + 1))); 
} 

在代碼中的註釋應該描述遞歸方法的行爲。如果您對此有疑問,請發表評論。

相關問題