字符串的處理(String下方法)
1)拿到某一個字符串後檢查是否是以某一個指定的字符串開頭
String.startsWith(“指定的字符串”)
public void startString() {
String attachmentPath = "file:C:\\Windows\\AppPatch\\Custom";
if (attachmentPath.startsWith("file:")) {
System.out.println("是以‘file:’開頭的!");
}
}
String.StartsWith(“指定的字符串”,“開始檢查的位置”);
public void startString() {
String attachmentPath = "file:C:\\Windows\\AppPatch\\Custom";
// 從第3個字符開始檢查
if (attachmentPath.startsWith("file:",3)) {
System.out.println("是以‘file:’開頭的!");
}
}
2)字符串截取
String.substring(“字符串開始截取位置”);
// 例如:
"string".substring(2); 返回 “ring”,從字符串的第二位開始截取後面的
3)字符串的替換
String.replaceAll(“匹配此字符串的正則表達式”,“用來替換每個匹配項的字符串”); 匹配失敗後返回原字符串
public void findByStr() {
String str = "bdaasfasfannnnnakkkdnasnl\\72";
// 將連續的重疊字符替換成“#”
// 不管重疊幾次都只替換成一個 #
String at = str.replaceAll("(.)\\1+", "#");
System.out.println(at);
}
結果: “ bd#sfasfa#a#dnasnl\72 ”
4)檢查字符串結尾是否以某一個字符串結尾
String.endsWith("結尾的字符串"); // 和檢查開始的同理