我正在尝试使用
StringBuilder
复制此代码,但无法弄清楚如何。
这样做是用字符串数组 (
tweetText
) 检查给定的字符串 (usernames
),如果匹配则替换字符串中的那个,在它之前添加一个“@”。
例如:
如果字符串是; DonaldTrump 和 JoeBiden 似乎都将在 2024 年竞选总统。
在用户名数组中是{“DonaldTrump”,“JoeBiden”}
结果应该是:看起来@DonaldTrump 和@JoeBiden 都将在 2024 年竞选总统。
这是我的代码,无需使用
StringBuilder
:
public String highlightUsernames(String tweetText, String[] usernames) {
String resultText = "" ;
for (int i = 0; i < usernames.length; i++) {
tweetText = tweetText.replace(usernames[i], "@"+usernames[i]);
}
return tweetText;
}
我不太了解
StringBuilder
是如何工作的...
在这种情况下使用 StringBuilder 会提供更好的性能。这是一个简单的实现:
public String highlightUsernames(String tweetText, String[] usernames) {
StringBuilder resultText = new StringBuilder(tweetText) ;
for (int i = 0; i < usernames.length; i++) {
var index = -1;
while (true) {
index = resultText.indexOf(usernames[i], index + 2);
if (index == -1)
break;
resultText.insert(index, "@");
}
}
return resultText.toString();
}
StringBuilder 类的目的是创建一个可变的字符序列,因为 String 类是不可变的。
我不认为你的情况是必要的,因为你可以使用这样的东西:
for( String username: usernames ) {
s = s.replace(username, "@" + username);
}
但假设目的是了解 StringBuilder 的工作原理,这里是一个使用 StringBuilder 类的更新函数:
public String highlightUsernames(String tweetText, String[] usernames) {
// You can create an instance of the StringBuilder class with the tweetText String.
StringBuilder stringBuilder = new StringBuilder(tweetText);
for (int i = 0; i < usernames.length; i++) {
// Get the index of the user
int index = stringBuilder.indexOf(usernames[i]);
// And use the insert method of StringBuilder to add the "@" before the username if it's found
if (index != -1) {
stringBuilder.insert(index, "@");
}
}
// At the end, you can convert the StringBuilder to a String, using its toString method
return stringBuilder.toString();
StringBuilder 是一个允许使用附加、替换等方法操作字符串的类。我认为没有必要将它用于此任务,因为有更简单的方法。 只需使用 String.replace 并将名称替换为前面的 @ 符号。
String[] names = {"DonaldTrump", "JoeBiden"};
String s = "It seems like DonaldTrump and JoeBiden will both run for president in 2024.";
for(String name : names) {
s = s.replace(name, "@"+name);
}
System.out.println(s);
版画
It seems like @DonaldTrump and @JoeBiden will both run for president in 2024.
如果要确保数组中的现有字符串没有以@符号为前缀,请使用 String.replaceAll
执行以下操作(?<!@)
- 是一个否定的后视断言,它说 @
不会出现在名字之前。
for (String name : names) {
s = s.replaceAll("(?<!@)"+name, "@"+name);
}