关于java:如何从字符串中获取子字符串

How to get substring from string

本问题已经有最佳答案,请猛点这里访问。

我有两根绳子

1
2
 1."151.909 KB"
 2."151.0"

在两种情况下,我应该把所有东西都切掉在.符号之后。结果我应该有下一个:

1
2
 1."151"
 2."151"


1
s.substring(0, s.indexOf("."));


1
2
3
String str ="150.23121KB";
String[] requiredString = str.split("\\.");
System.out.println(requiredString[0]);


使用这个String.indexOf

Returns the index within this string of the first occurrence of the specified character. If a character with value ch occurs in the character sequence represented by this String object, then the index (in Unicode code units) of the first such occurrence is returned. For values of ch in the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:

String.substring联合。

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

结果

1
s.substring(0, s.indexOf("."));

1
result = result.split("\\.")[0];