Java 检查字符串是否包含点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32167807/
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-08-11 12:06:33  来源:igfitidea点击:

Checking if a string contains a dot

javastring

提问by Robin De Baets

Today I was trying to detect if a string contains a dot, but my code isn't working

今天我试图检测一个字符串是否包含一个点,但我的代码不起作用

 String s = "test.test";
 if(s.contains("\.")) {
     System.out.printLn("string contains dot");
 }

采纳答案by HaveNoDisplayName

contains()method of String class does not take regular expression as a parameter, it takes normal text.

contains()String类的方法不以正则表达式为参数,它以普通文本为参数。

String s = "test.test";

if(s.contains("."))
{
    System.out.println("string contains dot");
}

回答by Luiggi Mendoza

String#containsreceives a plain CharacterSequencee.g. a String, not a regex. Remove the \\from there.

String#contains接收一个普通的CharacterSequence例如 a String,而不是一个正则表达式。\\从那里删除。

String s = "test.test";
if (s.contains(".")) {
    System.out.println("string contains dot");
}

回答by Jaeger Kor

You only need

你只需要

s.contains (".");

回答by svarog

Sometimes you will need to find a character and do something with it, a similar check can also be done using .indexOf('.'), for instance:

有时你需要找到一个字符并用它做一些事情,也可以使用类似的检查来完成.indexOf('.'),例如:

"Mr. Anderson".indexOf('.'); // will return 2

The method will return the index position of the dot, if the character doesn't exist, the method will return -1, you can later do a check on that.

该方法将返回点的索引位置,如果该字符不存在,该方法将返回-1,您可以稍后进行检查。

if ((index = str.indexOf('.'))>-1) { .. do something with index.. }

回答by Erangad

Try this,

尝试这个,

String k="test.test";
    String pattern="\.";
    Pattern p=Pattern.compile(pattern);
    Matcher m=p.matcher(k);
    if(m.find()){
        System.out.println("Contains a dot");
    }
}

回答by Demon App Programmer

The easiest way is to check with a .contains() statement.(.contains() only works for strings) From

最简单的方法是使用 .contains() 语句进行检查。(.contains() 仅适用于字符串)来自

 String s = "test.test";
 if(s.contains("\.")) {
     System.out.printLn("string contains dot");
 }

to

String s = "test.test";
 if(s.contains(".")) {
     System.out.printLn("string contains dot");
 }

Do like this to check any symbol or character in a string

这样做以检查字符串中的任何符号或字符