2014-04-22 26 views
0

我正在建立一個代表多項式的字符串。我試圖用「」替換所有^ 1和x^0以使用replaceAll方法簡化輸出。但是,當我運行代碼時,它不檢測任何目標字符串。Java的String.replaceAll不工作

public String toString() { 
     String output = ""; 
     boolean isFirst = true; 
     for(Node current = head; current != null; current = current.next) { 
      if(isFirst) { 
       output += current.coefficient + "x^" + current.exponent; 
       isFirst = false; 
      } 
      else if(current.coefficient < 0) 
       output += " - " + current.coefficient*-1 + "x^" + current.exponent; 
      else 
       output += " + " + current.coefficient + "x^" + current.exponent; 
     } 
     output.replaceAll("x^0", ""); 
     output.replaceAll("^1", ""); 
     return output; 
    } 
+3

這是您的標題中的一個大膽的聲明。更有可能你的代碼錯了... – Deduplicator

+1

Java 101:'字符串是不可變的。所有「修改」字符串的方法都沒有。他們返回一個新的字符串,這是一個原始的修改副本。 –

回答

3

字符串是不可變的。你不能改變一個字符串。因此,replacereplaceAll方法返回一個新的字符串。這裏試試這個:

output = output.replaceAll("x^0", ""); 
output = output.replaceAll("^1", ""); 
2

字符串是不可變的。如果您查看文檔,您會看到每個修改String內容的方法都會返回一個新的。

因此,您需要將replaceAll的結果返回至output

output = output.replaceAll("x^0", ""); 
3

因爲字符串是不可改變的,任何修改操作返回一個新的字符串。因此,你必須保存和使用功能的結果工作:

output = output.replace(...) 

另外,請看看定規範的允許的模式:http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

的一點我想調出的是一個^在字符串的開始處將模式錨定到字符串的開頭。你不想那樣,所以逃避它:\^

無論如何,你真的要刪除的通話replaceAll"x^1""x^10"開始處匹配!當你建立你的字符串時,不要包含這些子字符串。

double f = current.coefficient; 
if(isFirst) 
    isFirst = false; 
else if(f < 0) { 
    f = -f; 
    output += " - "; 
} else 
    output += " + "; 
output += f; 
if(current.exponent == 1) 
    output += "x"; 
else if(current.exponent != 0)