String 类型判断是否包含 - 字符
时间: 2023-07-27 15:18:13 浏览: 60
可以使用 String 类的 contains() 方法来判断一个字符串是否包含特定字符或子字符串。在本例中,可以使用以下代码来判断一个字符串是否包含 "-" 字符:
```java
String str = "example-string";
if (str.contains("-")) {
System.out.println("The string contains '-' character.");
} else {
System.out.println("The string does not contain '-' character.");
}
```
如果字符串包含 "-" 字符,它将输出 "The string contains '-' character.",否则它将输出 "The string does not contain '-' character."。
相关问题
string类型的list 如何判断是否存在 某个字符
您可以使用Python中的in关键字来判断字符串是否存在于列表中。示例代码如下:
```
my_list = ['apple', 'banana', 'orange']
if 'apple' in my_list:
print('apple is in the list')
else:
print('apple is not in the list')
```
如果您想要检查列表中的所有字符串是否包含特定字符,可以使用以下代码:
```
my_list = ['apple', 'banana', 'orange']
char = 'p'
for word in my_list:
if char in word:
print(f'{word} contains {char}')
else:
print(f'{word} does not contain {char}')
```
python string类型判断包含
在Python中,我们可以通过使用in操作符或find()函数来判断字符串是否包含另一个字符串。
使用in操作符时,我们可以使用以下语法:
```
if substring in string:
# code to execute if substring is found in string
```
这将检查字符串string中是否包含子字符串substring。如果是,则条件为真,代码块中的代码将被执行。
另一种方法是使用find()函数,该函数返回子字符串在字符串中的索引位置。如果子字符串不在字符串中,find()函数将返回-1。
```
index = string.find(substring)
if index != -1:
# code to execute if substring is found in string
```
这将返回子字符串在字符串中首次出现的索引位置或-1(如果它不是子字符串)。
我们还可以使用startswith()和endswith()函数来检查一个字符串是否以另一个字符串开头或结尾,例如:
```
if string.startswith(substring):
# code to execute if string starts with substring
if string.endswith(substring):
# code to execute if string ends with substring
```
总之,Python提供了多种方法来判断字符串是否包含另一个字符串,具体取决于您的需求和个人喜好。