Rose Robrecht
Rose Robrecht

Reputation: 23

How can I edit specific characters from a string within a separate method?

public static String replaceExclamation(String userText){
   int i = 0;
   for ( i=0; i < userText.length(); ++i) {
      char currentChar = userText.charAt(i);
      if (currentChar == '!') {
         userText.charAt(i) = ".";
      }
   }
   return userText;
}

I am trying to replace all the '!' in a string with a '.' but I am getting an unexpected type error.
What does this mean and how can I fix it?

Also, does the fact that userText is from main instead of this local method impact my ability to edit the string?

Upvotes: 2

Views: 84

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40048

String is immutable, if you replace any character in String then with that change new String object is created, so i prefer using StringBuilder for this

public static StringBuilder replaceExclamation(StringBuilder userText){
  int i = 0;
 for ( i=0; i < userText.length(); ++i) {
  char currentChar = userText.charAt(i);
  if (currentChar == '!') {
     userText.setCharAt(i,'.');
    }
  }
  return userText;
}

Or you can use replace(char oldChar, char newChar)

String result = userText.replace('!', '.');

Or you can use replaceAll(String regex, String replacement)

String result = userText.replaceAll("!", ".");

Upvotes: 2

Related Questions