-1

I am trying to replace the "," in the string with an empty string "". I believe the following code is correct, but when I run it with Eclipse. It doesn't work. What's wrong with my code and how should I correct it

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

3 Answers3

6

A Java String is immutable, so no function alters the String instance, just build a new one:

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

This applies to every method that should alter the content of the String itself in your example.

From Javadoc:

Strings are constant; their values cannot be changed after they are created.

Jack
  • 131,802
  • 30
  • 241
  • 343
4

changed your code to

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

You haven't assinged the value that's why

sasankad
  • 3,543
  • 3
  • 24
  • 31
0

I would do it like this -

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);
  }
}

Which prints my name identically (twice), that is -

firstname = 'Elliott', lastname = 'Frisch'
firstname = 'Elliott', lastname = 'Frisch'
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249