I have a string (which is basically a file name following a naming convention) abc.def.ghi
I would like to extract the substring before the first
look at String.indexOf
and String.substring
.
Make sure you check for -1 for indexOf
.
Here is code which returns a substring from a String
until any of a given list of characters:
/**
* 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);
}
The accepted answer is correct but it doesn't tell you how to use it. This is how you use indexOf and substring functions together.
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
}
How about using regex?
String firstWord = filename.replaceAll("\\..*","")
This replaces everything from the first dot to the end with "" (ie it clears it, leaving you with what you want)
Here's a test:
System.out.println("abc.def.hij".replaceAll("\\..*", "");
Output:
abc
This could help:
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;
}
In java.lang.String you get some methods like indexOf(): which returns you first index of a char/string. and lstIndexOf: which returns you the last index of String/char
From Java Doc:
public int indexOf(int ch)
public int indexOf(String str)
Returns the index within this string of the first occurrence of the specified character.