Answers:
接受的答案是正确的,但没有告诉您如何使用它。这是一起使用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 found.
//So check and account for it.
String subString;
if (iend != -1)
{
subString= filename.substring(0 , iend); //this will give abc
}
您可以只拆分字符串。
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
当然,为了清楚起见,它分为多行。它可以写成
String beforeFirstDot = filename.split("\\.")[0];
或者您可以尝试类似
"abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);
def.hij.klm什么?那么您的代码将如何工作?(您的代码仅适用于该示例-您最好编写一个返回的函数"abc"-它也将同样有效)
如何使用正则表达式?
String firstWord = filename.replaceAll("\\..*","")
这会将所有从第一个点到最后一个点的内容都替换为“”(即清除它,使您拥有所需的内容)
这是一个测试:
System.out.println("abc.def.hij".replaceAll("\\..*", "");
输出:
abc
以下是返回从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);
}
这可以帮助:
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;
}