2013-12-20 96 views
-1

我想用空字符串「」替換字符串中的「,」。 我相信下面的代碼是正確的,但是當我用Eclipse運行它時。它不起作用。這有什麼錯我的代碼和我應該怎麼糾正我應該如何替換空字符串的單個字符

String fullName = "lastname, firstname", lastName, firstName; 

    String[] parts = fullName.split(" "); 
    String firstPart = parts[0]; 
    String secondPart = parts[1]; 

    if (firstPart.contains(",")) { 
     firstPart.replace(",", ""); 
     firstPart.trim(); 
     secondPart.trim(); 
     lastName = firstPart; 
     firstName = secondPart; } 

回答

6

一個Java String是不變的值,所以沒有功能改變String實例,只是建立一個新的:

string = string.replace(",",""); 

這適用於在您的示例中應該更改String本身內容的每種方法。

Javadoc來自:

字符串是常數;它們的值在創建後無法更改。

+0

我明白了〜我忘了把它分配給一個變量改變它後大聲笑謝謝你的信息^ _ ^ – user2789240

4

改變你的代碼

firstPart = firstPart.replace(",","") 

您還沒有assinged這就是爲什麼

0

我會做這樣的 -

public static void main(String[] args) { 
    String[] names = new String[] { "Frisch, Elliott", 
     "Elliott Frisch" }; 
    for (String fullName : names) { 
    String last = ""; 
    String first = ""; 
    int p = fullName.indexOf(','); 
    if (p > -1) { 
     last = fullName.substring(0, p).trim(); 
     first = fullName.substring(p + 1, 
      fullName.length()).trim(); 
    } else { 
     p = fullName.indexOf(' '); 
     if (p > -1) { 
     first = fullName.substring(0, p).trim(); 
     last = fullName.substring(p + 1, 
      fullName.length()).trim(); 
     } 
    } 
    System.out.printf(
     "firstname = '%s', lastname = '%s'\n", 
     first, last); 
    } 
} 

哪些相同(兩次),也就是打印我的名字 -

firstname = 'Elliott', lastname = 'Frisch' 
firstname = 'Elliott', lastname = 'Frisch'