如何在Java中替换所有单词实例,只要它们不是其他单词的一部分?

huangapple go评论30阅读模式
英文:

How can I replace all instances of a word in Java as long as they're not part of other words?

问题

以下是翻译好的部分:

我是Java的初学者,想要问一下如何在字符串中将单词“is”替换为“is not”,但只有在它前后都不是另一个字母(数字和符号可以),并且它不是另一个单词的一部分。

例如,我想将每个字符串中的单词“is”替换为“is not”,但是如果不更改包含“is”的所有单词(例如“this”或“miss”)的话,就很难做到。

目前,当我尝试使用单词“this”来调用代码时,我的代码会陷入无限循环。(请参见下面的示例输出)
例如,这是我的代码:

public static String isReplace(String str) {
    String newStr = "";
    for (int i = 0; i < str.length(); i++) {
        
        if (str.charAt(i) == ('i') && str.charAt(i + 1) == ('s')) {
            if (!(Character.isLetter(str.charAt(i + 2)))) {
                str = str.replace("is", "is not");
            }
        }
        //break;
    }
    return str; // 修复我
}

isReplace("This is good")); // 应该得到“This is not good”

isReplace("is-is")); // 应该得到“is not-is not”
isReplace("My favorite food is9ie")) // 应该得到“My favorite food is not9ie”
英文:

I'm a beginner in Java and wanted to ask how we can replace the word "is" in a string with "is not" only while it's not preceded by or followed by another letter (numbers and symbols fine) and isn't a part of another word.

For example, I want to replace the word "is" with "is not" in every string, but it's difficult to do so without changing all words that contain "is" such as "this" or "miss".

Currently, my code gets stuck in an infinite loop when I try to use a word like "this" to call it. (see example outputs below)
For example, here is my code:

public static String isReplace(String str) {
	String newStr = &quot;&quot;;
	for (int i = 0; i &lt; str.length(); i++) {
		
		if (str.charAt(i) == (&#39;i&#39;) &amp;&amp; str.charAt(i + 1) == (&#39;s&#39;)) {
			if (!(Character.isLetter(str.charAt(i + 2)))) {
				str = str.replace(&quot;is&quot;, &quot;is not&quot;);
			}
		}
		//break;
	}
	return str ; // FIX ME
}

isReplace(&quot;This is good&quot;)); //should give me &quot;This is not good&quot;

isReplace(&quot;is-is&quot;)); //should give me &quot;is not-is not&quot;
isReplace(&quot;My favorite food is9ie&quot;)) // should give me &quot;My favorite food is not9ie&quot;

答案1

得分: 1

public class P1 {

    public static String isReplace(String str) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {

            char current = str.charAt(i);

            // if last character just add it to the buffer
            if (i == str.length() - 1) {
                sb.append(current);
            } else {
                char next = str.charAt(i + 1);
                if (current == 'i' && next == 's') {
                    // check if preceding character is not a letter and following character is not a letter
                    if ((i == 0 || !Character.isLetter(str.charAt(i - 1))) &&
                            ((i + 2 == str.length() || !Character.isLetter(str.charAt(i + 2)))) {
                        sb.append("is not");
                        i++;  // to skip reading 's' in the next iteration
                    } else {
                        sb.append(current);
                    }
                } else {
                    sb.append(current);
                }
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(isReplace("This is good"));
        System.out.println(isReplace("is-is"));
        System.out.println(isReplace("My favorite food is9ie"));
    }
}
This is not good
is not-is not
My favorite food is not9ie
英文:

Just added more refinement over your existing logic.

public class P1 {
public static String isReplace(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i &lt; str.length(); i++) {
char current = str.charAt(i);
//if last character just add it to the buffer
if(i == str.length()-1){
sb.append(current);
}else{
char next = str.charAt(i+1);
if(current == &#39;i&#39; &amp;&amp; next == &#39;s&#39;){
//check is preceding character is not letter and following character is not letter
if((i == 0 || !Character.isLetter(str.charAt(i-1))) &amp;&amp;
((i+2 == str.length() || !Character.isLetter(str.charAt(i+2))))){
sb.append(&quot;is not&quot;);
i++;  // to skip reading s in next iteration
}else{
sb.append(current);
}
}else{
sb.append(current);
}
}
}
return sb.toString() ;
}
public static void main(String[] args) {
System.out.println(isReplace(&quot;This is good&quot;));
System.out.println(isReplace(&quot;is-is&quot;));
System.out.println(isReplace(&quot;My favorite food is9ie&quot;));
}
}
This is not good
is not-is not
My favorite food is not9ie

答案2

得分: 1

以下是翻译好的内容:

可能最简单的方法是使用正则表达式。
通过这个搜索输入,它会搜索所有不被字母包围的“is”。

str.replaceAll("(?<![a-zA-Z])is(?![a-zA-Z])", "is not")

这是一个可行的示例:

public class Main {

  public static String isReplace(String string) {
    return string.replaceAll("(?<![a-zA-Z])is(?![a-zA-Z])", "is not");
  }

  public static void main(String[] args) {
    System.out.println(isReplace("This is good"));
    System.out.println(isReplace("My favorite food is9ie"));
    System.out.println(isReplace("is#is"));
  }
}

输出:

This is not good
is not#is not
My favorite food is not9ie

正则表达式解释:

(          打开第一个捕获组
?<!        负向回顾后断言。这将在搜索结果之前查找并检查以下字符是否不存在。
[a-zA-Z]   所有字母的字符集。
)          关闭第一个捕获组。
is         搜索“is”。
(          打开第二个捕获组。
?!         负向前瞻断言。这将在搜索结果之前查找并检查以下字符是否不存在。
[a-zA-Z]   所有字母的字符集。
)          关闭第二个捕获组。
英文:

Probably the easiest method is to use Regex.
With this search input, it searches for all "is" that are not surrounded by letters.

str.replaceAll(&quot;(?&lt;![a-zA-Z])is(?![a-zA-Z])&quot;, &quot;is not&quot;)

Here is a working example:

  public class Main {
public static String isReplace(String string) {
return string.replaceAll(&quot;(?&lt;![a-zA-Z])is(?![a-zA-Z])&quot;, &quot;is not&quot;);
}
public static void main(String[] args) {
System.out.println(isReplace(&quot;This is good&quot;));
System.out.println(isReplace(&quot;My favorite food is9ie&quot;));
System.out.println(isReplace(&quot;is#is&quot;));
}
}

Output:

This is not good
is not#is not
My favorite food is not9ie

Regex explained:

  (        Open the first capturing group
?&lt;!      Negative lookbehind. This will look before the search results and check that none of the following characters are there.
[a-zA-Z] Character set of all letters.
)        Close the first capturing group.
is       Searches for &quot;is&quot;.
(        Open the second capturing group.
?!       Negative lookahead. This will look ahead of the search results and check that none of the following characters are there.
[a-zA-Z] Character set of all letters.
)        Close the second capturing group.

huangapple
  • 本文由 发表于 2020年10月26日 14:22:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64532335.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定