java - 在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?
因为两者world
都you
在列表中。
传递"Hello"
将简单地返回未修改的字符串"Hello"
,因为里面的字符串中没有任何内容words
。
我该怎么做呢?我尝试对每个单词的字符串进行硬编码 .replaceAll() 调用,但随后我丢失了字符串的大小写。例如"Hello world how are you?"
变成"hello w*o*r*l*d how are y*o*u?"
解决方案
这段代码:
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?
推荐阅读
- google-apps-script - 使用 Google App Script 发布到 Bitly api 返回 403
- android - 发现多个文件的操作系统独立路径为“junit/runner/logo.gif”
- ocaml - 如何打印无符号 64 位整数
- c# - 使用 mvc 的实体框架 - 数据注释
- flutter - 如何在保持对话框打开的同时关闭抽屉?
- multithreading - 大型协程与许多小型协程?
- amazon-web-services - 具有此 ID 的 Terraform 资源不存在
- sql - 用两个查询计算平均值
- image - 包 cached_network_image 是否会减少 Firestore 存储的网络带宽量?
- java - 如何创建两个日志文件