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 16, 2018 in Java by 93.lynn
• 1,550 points
19 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 16, 2018 by geek.erkami
• 2,320 points

Related Questions In Java

0 votes
1 answer

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

myString=" Hello World"; myString.split("\\s+"); This should produce the strings "Hello" and "World" and omit ...READ MORE

answered May 23, 2018 in Java by sharth
• 3,320 points
33 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,840 points
33 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,840 points
216 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,040 points
548 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,040 points
124 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,520 points
71 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,840 points
179 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
• 520 points
55 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,320 points
41 views