好的,所以我尝试在您的帮助下学习更多有关 Java 中的字符串和链接字符串的知识。
现在我知道字符串是不可变的,但我很难做到这一点,例如:
Implement the method
public static String notReplace(String str)
The method takes a String as its input and returns a String in which every occurrence of the lowercase word "is" has been replaced with "is not". The word "is" should not 2 be immediately preceded or followed by a letter -- so for example the "is" in "this" should not be replaced. (Note:
Character.isLetter(char)
tests if a char is a letter.)
示例:
notReplace("是测试") → "不是测试"
notReplace("is-iswise") → "is not-isnotwise"
这是我写的:
public class NotReplace{
public static void main(final String[] args){
final String str2 = "is no";
System.out.println(notReplace(str2));
}
public static String notReplace(final String str){
final int times = str.length();
final StringBuilder sb = new StringBuilder(str);
for(int i = 0; i <= times; i++){
if((str.charAt(i) == 'i') && (str.charAt(i + 1) == 's')
&& !Character.isLetter(str.charAt(i + 2))){
sb.insert(i, "not");
}
final String str1 = sb.toString();
return str1;
}
}
}
我相信这完全是一团糟,我很乐意了解更多如何在这种情况下使用字符串。
谢谢
编辑:我无法使用replaceAll函数。
最佳答案
您可能会发现这很有趣
String text = "This is a test. It is"; // note the 'is' at the end.
String text2 = text.replaceAll("\\bis\\b", "is not");
System.out.println(text +" => "+text2);
打印
This is a test. It is => This is not a test. It is not
下面的方法可以实现这一点
public static String notReplace(final String str){
final StringBuilder sb = new StringBuilder()
.append(' ').append(str).append(" ");
for (int i = 0; i < sb.length() - 2; i++) {
if (!Character.isLetter(sb.charAt(i)) &&
sb.charAt(i + 1) == 'i' &&
sb.charAt(i + 2) == 's' &&
!Character.isLetter(sb.charAt(i + 3))) {
sb.insert(i + 3, " not");
i += 5;
}
}
return sb.substring(1, sb.length() - 1);
}
在开头和结尾添加空格以避免边界检查。
关于java 字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5355262/