逐个替换String的一部分

时间:2013-08-23 00:12:12

标签: android string replace contains

我有字符串:

  

Apple,Banana,Strawberry;柠檬,西瓜;橙

当我尝试这个时:

if(meaning.contains(";"))
        {
            meaning=meaning.replace(";", "\n");
        }

结果:

Apple, Banana, Strawberry  
 Lemon, Watermelon  
 Orange

如何逐个替换部分字符串以替换“;”到“\ n”+ numStr?

1.Apple, Banana, Strawberry  
2.Lemon, Watermelon  
3.Orange

2 个答案:

答案 0 :(得分:1)

没有测试,但应该有效:

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();

答案 1 :(得分:1)

您可以使用以下代码。诀窍是使用String.split()而不是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());
}

结果将打印出来:

  1.苹果,香蕉,草莓
  2.柠檬,西瓜
  3.Orange