[英]alternate method for using substring on a String
我有一個包含下划線的字符串,如下所示:
123445_Lisick
我想在下划線之后從字符串中刪除所有字符。 我已經嘗試過下面的代碼,它可以工作,但是還有其他方法可以執行此操作,因為我需要將此邏輯放在for
循環中以從ArrayList中提取元素。
public class Test {
public static void main(String args[]) throws Exception {
String str = "123445_Lisick";
int a = str.indexOf("_");
String modfiedstr = str.substring(0, a);
System.out.println(modfiedstr);
}
}
另一種方法是使用split
方法。
String str = "123445_Lisick";
String[] parts = string.split("_");
String modfiedstr = parts[0];
我認為那真的買不到任何東西。 您使用的方法確實沒有錯。
您的方法很好。 盡管沒有在API文檔中明確說明,但我認為可以肯定indexOf(char)將在O(n)時間運行。 由於您的字符串是無序的,並且您不知道下划線的先驗位置,因此您無法避免此線性搜索時間。 完成搜索后,將需要提取子字符串以用於將來的處理。 對於這樣的簡單操作,通常可以安全地假設使用某種語言進行了合理完善的語言,而該函數已經過優化。
但是請注意,您是在隱式假設
如果這些假設中的任何一個都不總是成立,則您需要進行調整以應對這些情況。 在這兩種情況下,您都至少應防御性地檢查一下indexAt(char)返回的-1,以指示字符串中沒有'_'。 假設在這種情況下需要整個String,則可以使用如下所示的內容:
public static String stringAfter(String source, char delim) {
if(source == null) return null;
int index = source.indexOf(delim);
return (index >= 0)?source.substring(index):source;
}
您還可以使用類似的方法:
public class Main {
public static void main(String[] args) {
String str = "123445_Lisick";
Pattern pattern = Pattern.compile("^([^_]*).*");
Matcher matcher = pattern.matcher(str);
String modfiedstr = null;
if (matcher.find()) {
modfiedstr = matcher.group(1);
}
System.out.println(modfiedstr);
}
}
正則表達式將從輸入字符串的開始到找到一個非_
的字符對模式進行分組。
但是,正如蜥蜴@Bill所寫的那樣,我認為您現在使用的方法沒有任何問題。 我會以與您相同的方式進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.