java 审查词条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27242582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:28:24  来源:igfitidea点击:

Censored Words Condition

java

提问by beginnercoder010812

I need this program to print "Censored" if userInput contains the word "darn", else print userInput, ending with newline.

如果 userInput 包含单词“darn”,我需要这个程序打印“Censored”,否则打印 userInput,以换行符结尾。

I have:

我有:

import java.util.Scanner;

public class CensoredWords {
    public static void main (String [] args) {
        String userInput = "";
        Scanner scan = new Scanner(System.in);
        userInput = scan.nextLine;

        if(){
            System.out.print("Censored");
        }    
        else{
            System.out.print(userInput);
        }

        return;
    }
}

Not sure what the condition for the if can be, I don't think there is a "contains" method in the string class.

不确定 if 的条件是什么,我认为字符串类中没有“包含”方法。

回答by TheLostMind

The best solution would be to use a regex with word boundary.

最好的解决方案是使用带有字边界的正则表达式。

if(myString.matches(".*?\\bdarn\\b.*?"))

if(myString.matches(".*?\\bdarn\\b.*?"))

This prevents you from matching sdarnsas a rudeword. :) demo here

这可以防止您将其匹配sdarns粗鲁的词。:) 演示在这里

回答by Sarthak Mittal

Try this:

试试这个:

if(userInput.contains("darn"))
{
System.out.print("Censored");
}

Yes that's right, String class has a method called contains, which checks whether a substring is a part of the whole string or not

是的,没错,String 类有一个名为 contains 的方法,它检查子字符串是否是整个字符串的一部分

回答by maxx777

Java String Class does have a containsmethod. It accepts a CharSequenceobject. Check the documentation.

Java String 类确实有一个contains方法。它接受一个CharSequence对象。检查文档

回答by Cat

Another beginner method would be to use the indexOf function. Try this:

另一种初学者方法是使用 indexOf 函数。试试这个:

          if (userInput.indexOf("darn") > 0) {
             System.out.println("Censored");
          }

          else {
             System.out.println(userInput);