今天在对一个字符串进行操作的时候比较悲剧,基础不牢固,捣鼓了半天。
public class StringTest { public static void main(String[] args) { String path="/mnt/sdcard/gao.txt"; path.replaceFirst("/mnt", ""); System.out.println(path); String pathSub="/mnt/sdcard/gao.txt"; pathSub.substring(3, pathSub.length()); System.out.println(pathSub); } }
期望了结果是:
/sdcard/gao.txt /sdcard/gao.txt
但是实际的结果却是:
/mnt/sdcard/gao.txt /mnt/sdcard/gao.txt
看一下API的解释:
String java.lang.String.replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
An invocation of this method of the form str.replaceFirst(regex, repl) yields exactly the same result as the expression
java.util.regex.Pattern.compile(regex).matcher(str).replaceFirst(repl)
Parameters:
regex the regular expression to which this string is to be matched
replacement
Returns:
The resulting String
这下该明白了是返回的那个值才是想要的结
修改后:
String pathSub="/mnt/sdcard/gao.txt"; pathSub=pathSub.substring(3, pathSub.length()); System.out.println(pathSub);
满以为这下返回的结果该是:/sdcard/gao.txt,可是返回的结果却是:t/sdcard/gao.txt
再看一下API的解释:
String java.lang.String.substring(int beginIndex, int endIndex)
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.
Examples:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
Parameters:
beginIndex the beginning index, inclusive.
endIndex the ending index, exclusive.
Returns:
the specified substring.