java,取字符串中-符号之前的字符
时间: 2024-01-28 17:05:51 浏览: 80
可以使用String类的substring和indexOf方法来取字符串中-符号之前的字符。示例代码如下:
```java
public class Main {
public static void main(String[] args) {
String str = "abc-def-ghi";
String beforeDash = str.substring(0, str.indexOf("-"));
System.out.println(beforeDash);
}
}
```
运行结果为:
```
abc
```
在示例代码中,我们定义了一个字符串str,然后使用substring方法来截取字符串中从0到第一个-符号之前的字符,即abc。substring方法的第一个参数是截取的起始位置(包含),第二个参数是截取的结束位置(不包含)。我们使用indexOf方法来获取字符串中第一个-符号的位置,并将其作为substring方法的第二个参数。
需要注意的是,如果字符串中没有-符号,indexOf方法会返回-1,此时截取的字符串将是空字符串。可以根据具体需求进行处理。
阅读全文
相关推荐













