Odpowiedzi:
Przyjęta odpowiedź jest poprawna, ale nie mówi, jak z niej korzystać. W ten sposób używasz razem funkcji indexOf i podciąg.
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 found.
//So check and account for it.
String subString;
if (iend != -1)
{
subString= filename.substring(0 , iend); //this will give abc
}
Możesz po prostu podzielić ciąg ...
public String[] split(String regex)
Zwróć uwagę, że java.lang.String.split używa wartości wyrażenia regularnego separatora. Zasadniczo w ten sposób ...
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
Oczywiście jest to podzielone na wiele linii dla jasności. Można to zapisać jako
String beforeFirstDot = filename.split("\\.")[0];
Jeśli Twój projekt już używa commons-lang , StringUtils zapewnia przyjemną metodę do tego celu:
String filename = "abc.def.ghi";
String start = StringUtils.substringBefore(filename, "."); // returns "abc"
lub możesz spróbować czegoś takiego
"abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);
def.hij.klm? Jak wtedy działałby twój kod? (Twój kod działa tylko w tym jednym przykładzie - równie dobrze możesz napisać funkcję, która zwraca "abc"- działałaby równie dobrze)
A co powiesz na użycie wyrażenia regularnego?
String firstWord = filename.replaceAll("\\..*","")
Spowoduje to zastąpienie wszystkiego, od pierwszej kropki do końca, znakiem „” (czyli wyczyści go, pozostawiając Ci to, czego chcesz)
Oto test:
System.out.println("abc.def.hij".replaceAll("\\..*", "");
Wynik:
abc
W java.lang.String otrzymujesz metody, takie jak indexOf (): która zwraca pierwszy indeks znaku / ciągu znaków. i lstIndexOf: który zwraca ostatni indeks String / char
Z dokumentu Java:
public int indexOf(int ch)
public int indexOf(String str)
Zwraca indeks pierwszego wystąpienia określonego znaku w tym ciągu .
Oto kod, który zwraca podłańcuch od a Stringdo dowolnego z podanych znaków:
/**
* 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);
}
To może pomóc:
public static String getCorporateID(String fileName) {
String corporateId = null;
try {
corporateId = fileName.substring(0, fileName.indexOf("_"));
// System.out.println(new Date() + ": " + "Corporate:
// "+corporateId);
return corporateId;
} catch (Exception e) {
corporateId = null;
e.printStackTrace();
}
return corporateId;
}