用自动递增的数字替换字符串中的特定模式

时间:2009-08-30 18:07:18

标签: java

我有一个像"Hello how Hello are Hello"这样的字符串 我想用自动递增的数字替换上面字符串中"Hello"出现的次数。

结果如下:"1 how 2 are 3"

"Hello"可以多次出现

2 个答案:

答案 0 :(得分:1)

我不知道有必要用递归来做。

public class StringReplacement {

    private static final String HELLO = "Hello";

    /**
     * @param args
     */
    public static void main(String[] args) {
        String stringToTransform = "Hello how Hello are Hello";
        System.out.println(transform(stringToTransform));
    }

    private static String transform(String stringToTransform) {
        return transform(stringToTransform, 1);
    }

    private static String transform(String stringToTransform, int counter) {

        String output = stringToTransform.replaceFirst(HELLO, String
                .valueOf(counter));

        if (output.contains(HELLO))
            return transform(output, ++counter);
        else
            return output;
    }

}

答案 1 :(得分:0)

尝试这个简单的方法:

public static String transform(String input) {
    StringBuilder stringBuilder = new StringBuilder();
    int i = 1;

    for (String s : input.split("Hello")) {
        stringBuilder.append(String.format("%s %d", s, i++));
    }

    return stringBuilder.toString();
}

样本用法

public static void main(String[] args) {
    String i = "Hello how Hello are Hello";
    System.out.println(transform(i));
}