Java 如何用空字符串替换单个字符

Java 如何用空字符串替换单个字符,java,string,split,trim,Java,String,Split,Trim,我试图用空字符串“”替换字符串中的“”。 我相信下面的代码是正确的,但是当我使用Eclipse运行它时。它不起作用。我的代码有什么问题,应该如何更正 String fullName = "lastname, firstname", lastName, firstName; String[] parts = fullName.split(" "); String firstPart = parts[0]; String secondPart = parts[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;  }
将代码更改为

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

您没有分配值,这就是为什么Java
字符串是不可变的,因此没有函数更改
字符串
实例,只需构建一个新实例:

string = string.replace(",","");
这适用于在您的示例中应该更改
字符串本身内容的每个方法

发件人:

字符串是常量;它们的值在创建后无法更改


我会这样做-

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'

啊,我明白了~修改后我忘了给变量赋值了。哈哈,谢谢你提供的信息^_^