Reputation: 5083
I have string:
Apple, Banana, Strawberry; Lemon, Watermelon; Orange
When I try this:
if(meaning.contains(";"))
{
meaning=meaning.replace(";", "\n");
}
Result:
Apple, Banana, Strawberry
Lemon, Watermelon
Orange
How to replace part of String one by one in order to replace ";" to "\n"+numStr?
1.Apple, Banana, Strawberry
2.Lemon, Watermelon
3.Orange
Upvotes: 0
Views: 100
Reputation: 1048
Didn't test it, but should work:
String[] lines = meaning.split(";");
StringBuilder res = new StringBuilder();
for (int i = 0, size = lines.length; i < size; i++) {
res.append(i + 1).append(". ").append(lines[i]).append("\n");
}
res.toString();
Upvotes: 1
Reputation: 36289
You can use the following code. The trick is to use String.split()
instead of String.replace()
.
if(meaning.contains(";"))
{
StringBuilder builder = new StringBuilder();
String[] meanings = meaning.split(";");
for (int i = 0; i < meanings.length; i++) {
builder.append(String.format(Locale.US, "%d. %s\n", i, meanings[i].trim()));
}
Log.d("meanings", builder.toString());
}
The result will print:
1.Apple, Banana, Strawberry
2.Lemon, Watermelon
3.Orange
Upvotes: 1