Java在字符串中搜索
所以我想搜索一个字符串,看看它是否包含我要查找的子字符串。这是我写的算法:Java在字符串中搜索,java,search,Java,Search,所以我想搜索一个字符串,看看它是否包含我要查找的子字符串。这是我写的算法: //Declares the String to be searched String temp = "Hello World?"; //A String array is created to store the individual //substrings in temp String[] array = temp.split(" "); //Iterates
//Declares the String to be searched
String temp = "Hello World?";
//A String array is created to store the individual
//substrings in temp
String[] array = temp.split(" ");
//Iterates through String array and determines if the
//substring is present
for(String a : array)
{
if(a.equalsIgnoreCase("hello"))
{
System.out.println("Found");
break;
}
System.out.println("Not Found");
}
这个算法适用于hello,但我不知道如何让它适用于world,因为它附带了一个问号
谢谢你的帮助 看看:
要获得containsIgnoreCase,您必须将searchword和字符串设置为小写
看看这个答案:
以下情况也是如此:
世界大战,因为它会发现世界。如果你不想要这种行为,你必须像@Bart Kiers说的那样改变你的方法。看看:
要获得containsIgnoreCase,您必须将searchword和字符串设置为小写
看看这个答案:
以下情况也是如此:
世界大战,因为它会发现世界。如果你不想要这种行为,你必须改变你的方法,就像@Bart Kiers所说的那样。在以下方面进行拆分:
"[\\s?.!,]"
它匹配任何空格字符、问号、圆点、感叹号或逗号,如果您愿意,可以添加更多字符
或者对以下内容执行temp=temp.toLowerCase,然后执行temp.containsworld.拆分:
"[\\s?.!,]"
它匹配任何空格字符、问号、圆点、感叹号或逗号,如果您愿意,可以添加更多字符
或者先执行temp=temp.toLowerCase,然后执行temp.containsworld。您不必这样做,它已经实现了:
您不必这样做,它已经实现了: 您可能需要使用:
String string = "Hello World?";
boolean b = string.indexOf("Hello") > 0; // true
若要忽略大小写,必须使用正则表达式
b = string.matches("(?i).*Hello.*");
另一种可忽略的情况是:
// To ignore case
b=string.toLowerCase().indexOf("Hello".toLowerCase()) > 0 // true
您可能需要使用:
String string = "Hello World?";
boolean b = string.indexOf("Hello") > 0; // true
若要忽略大小写,必须使用正则表达式
b = string.matches("(?i).*Hello.*");
另一种可忽略的情况是:
// To ignore case
b=string.toLowerCase().indexOf("Hello".toLowerCase()) > 0 // true
你们的意思是世界应该和世界匹配吗????是的,我希望它忽略问号。你是说世界应该和世界匹配吗????是的,我希望它忽略问号..contains是casesensetive,而OP使用equalsIgnoreCase。也许有用你是对的。但在同一位置,您可以将方法fin设置为小写。但是我会修正我的答案。在temp=hell-worldie的情况下,这是错误的,要么是hell,要么是worldie,这取决于s1是用户控制的字符串,要么输入将产生true。是的,但它是为此而要求的,我想:“这个算法适用于hello,但我不知道如何让它适用于world,因为它附带了一个问号。”。contains是casesensetive,而OP使用equalsIgnoreCase。也许有用你是对的。但在同一位置,您可以将方法fin设置为小写。但我会修正我的答案。在temp=hell-worldie的情况下,这是错误的,要么是hell,要么是worldie,这取决于s1是用户控制的字符串,要么输入将产生true。是的,但有人问它,我想:“这个算法适用于hello,但我不知道如何让它适用于world,因为它附加了一个问号。”