startswith怎么用
时间: 2023-07-03 07:10:48 浏览: 49
startsWith() 是一个 Java 字符串方法,用于检查一个字符串是否以指定的前缀开头。它的语法如下:
```
public boolean startsWith(String prefix)
```
其中,prefix 是一个字符串,表示要检查的前缀。
例如,我们可以使用 startsWith() 方法检查一个字符串是否以指定的前缀 "Hello" 开头:
```
String str = "Hello, world!";
if (str.startsWith("Hello")) {
System.out.println("The string starts with 'Hello'.");
} else {
System.out.println("The string does not start with 'Hello'.");
}
```
上述代码会输出:The string starts with 'Hello'。
我们也可以指定一个起始位置来检查字符串的前缀,例如:
```
String str = "Hello, world!";
if (str.startsWith("world", 7)) {
System.out.println("The string starts with 'world' at position 7.");
} else {
System.out.println("The string does not start with 'world' at position 7.");
}
```
上述代码会输出:The string starts with 'world' at position 7.。这里的 7 表示从字符串的第七个字符开始检查。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)