user868935
user868935

Reputation:

Replace specific character in String with String?

I have a string thats a sentence and I would like to replace all instances of the character 't' with a string "foo" and 'h' with "bar".

String sentence = "The tea is hot.";

The ending result I'm trying to achieve:

"The fooea is fooobar."

Is this possible?

Upvotes: 1

Views: 195

Answers (2)

arshajii
arshajii

Reputation: 129477

Use replace:

sentence = sentence.replace("t", "foo").replace("h", "bar");

replaceAll takes a regular expressions when it is not needed here (and will therefore not be as efficient as replace).


Relevant documentation

Upvotes: 1

sampson-chen
sampson-chen

Reputation: 47269

Since this sounds like homework, I won't give a full solution.

But here is a very, very strong hint: replaceAll()

Upvotes: 1

Related Questions