我有一個字符串(這基本上是一個文件名以下的命名約定)abc.def.ghi
在java中如何從字符串獲得子串直到字符c?
我想第一.
(即點)之前提取子
在Java文檔API,我可以在String中似乎找不到一種方法。
我錯過了什麼嗎?怎麼做?
我有一個字符串(這基本上是一個文件名以下的命名約定)abc.def.ghi
在java中如何從字符串獲得子串直到字符c?
我想第一.
(即點)之前提取子
在Java文檔API,我可以在String中似乎找不到一種方法。
我錯過了什麼嗎?怎麼做?
請看String.indexOf
和String.substring
。
請確保您檢查了indexOf
的-1。
?
String firstWord = filename.replaceAll("\\..*","")
這取代了從第一個點到最後以「」(即,它會清除它,讓你與你想要的)
這是一個測試:
System.out.println("abc.def.hij".replaceAll("\\..*", "");
輸出:
abc
在java.lang.String中你得到的indexOf()的一些方法:返回你的茶第一指數R /串。 和lstIndexOf:返回字符串你/焦炭
的最後一個索引從Java文件:
public int indexOf(int ch)
public int indexOf(String str)
返回此字符串的第一次出現指定字符的處的索引。
你可以split字符串..
public String[] split(String regex)
注意java.lang.String.split使用分隔符的正則表達式的值。 基本上像這樣...
String filename = "abc.def.ghi"; // full file name
String[] parts = filename.split("\\."); // String array, each element is text between dots
String beforeFirstDot = parts[0]; // Text before the first dot
當然,這被分成多行clairity。它可以寫成
String beforeFirstDot = filename.split("\\.")[0];
您的提議不正確,因爲java.lang.String.split需要使用正則表達式值作爲屬性,而不僅僅是字符串。全部「。」在您的示例中需要更改爲「\\」。然後它會工作:) –
我喜歡正則表達式,但是每次都能讓我感到滿意。 –
如果你的項目已經使用commons-lang,StringUtils的用於此目的提供了一個很好的方法:
String filename = "abc.def.ghi";
String start = StringUtils.substringBefore(filename, "."); // returns "abc"
接受的答案是正確的,但它並沒有告訴你如何使用它。這就是你如何一起使用indexOf和substring函數。
String filename = "abc.def.ghi"; // full file name
int iend = filename.indexOf("."); //this finds the first occurrence of "."
//in string thus giving you the index of where it is in the string
// Now iend can be -1, if lets say the string had no "." at all in it i.e. no "." is not found.
//So check and account for it.
if (iend != -1)
String subString= filename.substring(0 , iend); //this will give abc
這是無效的代碼,因爲您不能在無花括號的If語句的主體中放置變量聲明。 – Clashsoft
這裏是代碼,返回從String
一子,直到任何字符的一個給定的名單:
/**
* Return a substring of the given original string until the first appearance
* of any of the given characters.
* <p>
* e.g. Original "ab&cd-ef&gh"
* 1. Separators {'&', '-'}
* Result: "ab"
* 2. Separators {'~', '-'}
* Result: "ab&cd"
* 3. Separators {'~', '='}
* Result: "ab&cd-ef&gh"
*
* @param original the original string
* @param characters the separators until the substring to be considered
* @return the substring or the original string of no separator exists
*/
public static String substringFirstOf(String original, List<Character> characters) {
return characters.stream()
.map(original::indexOf)
.filter(min -> min > 0)
.reduce(Integer::min)
.map(position -> original.substring(0, position))
.orElse(original);
}
簡短而親切。還要記住indexOf給出了子串的第一個索引。 –