1

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?

10
  • 4
    Yes it is possible. What have you tried? And shouldn't your end result be - "The fooea is barofoo."? Commented Dec 7, 2012 at 22:21
  • You need: - String#replace method. Commented Dec 7, 2012 at 22:24
  • @RohitJain it should actually be: Tbare fooea is barofoo. Commented Dec 7, 2012 at 22:25
  • No, it should be "Tbare fooea is barofoo." Commented Dec 7, 2012 at 22:25
  • 1
    @CodeAddict. No, OP is not replacing T, only t. Commented Dec 7, 2012 at 22:28

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

3 Comments

Homework on strings when college semesters across the US is ending? I think not
Neither we know your College Semesters is getting over, nor we know you live in US. But, regardless of that, we don't really give out direct solutions.
Why use replaceAll? Regex is not required here, replace() will do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.