Replacing a String with a character

0 votes

In my program, I am trying to replace “and” by a comma(“,”) using the String replace() method. But it's not working properly. Below is my code, can someone help me by pointing out what I am missing here?

String sentence = "One, Two, Three, Four and Five"
if (sentence.contains("and")){
    sentence.replace("and", ",");
}

May 17, 2018 in Java by 93.lynn
• 1,600 points
641 views

1 answer to this question.

0 votes

Yes, you are missing out on a very important concept.

Since Strings are immutable, i.e you cannot change the values of an existing object. And in your code, you are discarding the value, returned by the replace().

So, what you need to do is:

//You do not need the if statement

String demo = "One, Two, Three, Four and Five" ;

demo = demo.replace(“and”, “,”);

Hope this helps!

answered May 17, 2018 by geek.erkami
• 2,680 points

Related Questions In Java

0 votes
2 answers

How can I split the String with any whitespace character as delimiter?

String string = "Today's weather"; String[] arrayOfString = ...READ MORE

answered Aug 23, 2019 in Java by Sirajul
• 59,230 points
1,148 views
0 votes
2 answers

How to find out a single character appears in String or not in Java?

You can use string.indexOf('s'). If the 's' is present in string, ...READ MORE

answered Aug 7, 2018 in Java by Sushmita
• 6,920 points
5,749 views
0 votes
2 answers

How to left pad a string with zero in java?

String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0") the second ...READ MORE

answered Aug 31, 2018 in Java by Sushmita
• 6,920 points
3,207 views
0 votes
1 answer
0 votes
3 answers

Check if a String is numeric in Java

Java 8 Lambda Expression is used: String someString ...READ MORE

answered Sep 3, 2018 in Java by Daisy
• 8,140 points
3,726 views
0 votes
2 answers

Generate an alpha-numeric string randomly

Java supplies a way of doing this ...READ MORE

answered Jul 18, 2018 in Java by Daisy
• 8,140 points
2,652 views
0 votes
1 answer

How do I create a Java string from the contents of a file?

If you're looking for an alternative that ...READ MORE

answered Apr 19, 2018 in Java by Rishabh
• 3,620 points
1,205 views
0 votes
2 answers

Counting no of Occurrence of a particular character inside a string in Java

We can find out the no. of ...READ MORE

answered Sep 7, 2018 in Java by Sushmita
• 6,920 points
2,812 views
0 votes
2 answers

Java enum lookup using a String

Check this...Java Enum in details READ MORE

answered Dec 4, 2018 in Java by allenvarna
• 540 points
989 views
0 votes
1 answer

Join array elements with a separator in Java

Using Java 8, you can easily perform ...READ MORE

answered Aug 16, 2018 in Java by geek.erkami
• 2,680 points
2,836 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP