ina26
ina26

Reputation: 41

Understanding the method removeChar

At school we were looking at a code for removing a character from a string. I have a problem understanding the for loop in this code. What happens if word.charAt(i) is equal to c? If word.charAt(i) is not equal to c the character is printed out. (words.charAt(i) gets printed out) But if it is equal to c, where in the code does the character get removed?

Thank you in advance for your help. And I'm sorry for my bad English. This is the code our teacher gave us:

String removeChar(String word, char c) {
  String result = "";
  for (int i = 0; i<word.length();i++) {
    if (word.charAt(i) !=c) {
      result += word.charAt(i);
    }
  }
  return result;
}

Upvotes: 2

Views: 729

Answers (4)

Bahubali Kumar
Bahubali Kumar

Reputation: 1

Character is not actually removed its just been appended to the empty new string(String result = "";) which you have declared above,when word doesn't contain the character 'c', then those characters are getting appended to result, finally you are retrieving that 'Result' string not 'Word',it still containing same value which you have sent.

Upvotes: -1

Przemysław Moskal
Przemysław Moskal

Reputation: 3609

You can read this code like:

  1. Create an empty String result.
  2. For each letter from word, check if it is not 'c' character. Only if it is not 'c', append this letter to result String (add this letter at the end of result String). If currently checked character is equal to 'c', do nothing.
  3. When loop reaches the end of word, return result String.

By the way, appending String in a loop using += operator is not that efficient like using class StringBuilder and its append() method.

Upvotes: 3

Anton Tupy
Anton Tupy

Reputation: 969

This code just creates new String object (see variable result). At end of function this new string contains only characters which do not equal to c. Next it string returns as result of function.

Java strings is not mutable, so this is only way to "modify" string - create brand new string.

Upvotes: 0

S-Wing
S-Wing

Reputation: 579

The char is not really removed; it's simply not append (result += word.charAt(i)) into the string result. In this way the string that is returned by the method is formed only by the chars that are different from char c.

Upvotes: 2

Related Questions