string.contains比对中文返回false
时间: 2023-10-29 21:05:56 浏览: 32
`string.contains` 方法在比对中文时会出现问题,因为中文是使用多个字符组成的,而 `contains` 方法是基于字符的比对,所以无法正确匹配中文。为了解决这个问题,可以使用其他方法,例如 `string.indexOf` 方法或正则表达式匹配。请注意,如果要使用正则表达式匹配中文,需要使用 Unicode 编码。
相关问题
string.contains示例
以下是一个示例,演示如何使用`string.contains`方法检查一个字符串是否包含特定的子字符串:
```java
String message = "Hello, world!";
if(message.contains("world")) {
System.out.println("The message contains the word 'world'");
} else {
System.out.println("The message does not contain the word 'world'");
}
```
在这个例子中,我们首先定义了一个字符串`message`,它包含一条消息。然后,我们使用`message.contains`方法来检查这个字符串是否包含特定的子字符串`"world"`。如果包含,则输出一条消息,否则输出另一条消息。
请注意,`string.contains`方法区分大小写,因此如果您搜索的子字符串的大小写与实际字符串不匹配,则它将不会被找到。如果您需要不区分大小写的搜索,您可以使用`string.toLowerCase`或`string.toUpperCase`方法将字符串转换为统一的大小写,然后对其进行搜索。
String.contains
The method String.contains() is a built-in method in Java that is used to check whether a specific sequence of characters is present in a given string or not. It returns a boolean value true if the specified sequence of characters is found in the given string, otherwise it returns false.
Syntax:
public boolean contains(CharSequence sequence)
Parameters:
sequence: A sequence of characters to be searched in the given string. It can be a string, StringBuffer, or StringBuilder.
Return Value:
The method returns a boolean value that indicates whether the specified sequence of characters is found in the given string or not. It returns true if the sequence is found, otherwise false.
Example:
String str = "Hello World";
boolean result = str.contains("World");
System.out.println(result);
Output:
true