首页 > 解决方案 > 在Java中字符串的子字符串之间注入字符

问题描述

我有一个存储在列表中的单词列表,单词。

private String[] words = new String[]{"world", "you"};

然后我有一个字符串,helloWorld

private String helloWorld = "Hello world how are you?";

我想创建一个函数,它将接受一个字符串(在本例中为 helloWorld),它会不区分大小写地查看words列表中是否存在任何字符串。如果有,它将*在匹配字符串的每个字母之间放置一个字符。

例如输出将是

Hello w*o*r*l*d how are y*o*u?因为两者worldyou在列表中。

传递"Hello"将简单地返回未修改的字符串"Hello",因为里面的字符串中没有任何内容words

我该怎么做呢?我尝试对每个单词的字符串进行硬编码 .replaceAll() 调用,但随后我丢失了字符串的大小写。例如"Hello world how are you?"变成"hello w*o*r*l*d how are y*o*u?"

标签: javastring

解决方案


这段代码:

private static String[] words = new String[]{"world", "you"};
private static String helloWorld = "Hello world how are you?";

public static String getHello() {
    String s = helloWorld;
    for (String word : words) {
        int index = s.toLowerCase().indexOf(word.toLowerCase());
        if (index >= 0) {
            String w = s.substring(index, index + word.length());
            StringBuilder sb = new StringBuilder();
            sb.append(s.substring(0, index));
            for (int i = 0; i < w.length(); i++) {
                sb.append(w.charAt(i));
                if (i < w.length() - 1)
                    sb.append("*");
            }
            sb.append(s.substring(index + w.length()));
            s = sb.toString();
        }
    }
    return s;
}

public static void main(String[] args) {
    System.out.println(getHello());
}

印刷:

Hello w*o*r*l*d how are y*o*u?

推荐阅读