Java 我想得到子字符串

Java 我想得到子字符串,java,string,rcp,Java,String,Rcp,目前我正在使用这样的代码 while (fileName.endsWith(".csv")) { fileName = fileName.substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV)); if (fileName.trim().isEmpty()) { throw new IllegalArgumentException(); } } 当用户以小写字母

目前我正在使用这样的代码

    while (fileName.endsWith(".csv")) {
        fileName = fileName.substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV));
        if (fileName.trim().isEmpty()) {
            throw new IllegalArgumentException();
        }
    }
当用户以小写字母(.csv)指定扩展名时,上面的代码可以正常工作,但windows接受区分大小写的扩展名,因此他可以给出.csv、.csv等扩展名。我如何更改上面的代码


提前谢谢你为什么不把它改成小写

while (fileName.toLowerCase().endsWith(".csv")) {
    fileName = fileName.substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV));
    if (fileName.trim().isEmpty()) {
        throw new IllegalArgumentException();
    }
}

您可以将两者都转换为大写

所以改变这条线

fileName = fileName.substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV));

你可以这样试试

 int lastIndexOfDot=fileName.lastIndexOf("\\.");
 String fileExtension=fileName.substring(lastIndexOfDot+1,fileName.length()); 
 while(fileExtension.equalsIgnoreCase(".csv")){

 } 


请将其转换为小写,然后进行比较

  while (fileName.toLowerCase().endsWith(".csv")) {
        fileName = fileName.toLowerCase().substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV));
        if (fileName.toLowerCase().trim().isEmpty()) {
            throw new IllegalArgumentException();
        }
    }

深夜正则表达式解决方案:

Pattern pattern = Pattern.compile(".csv", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(fileName);
while (matcher.find()) {
    fileName = fileName.substring(0, matcher.start());
    if (fileName.trim().isEmpty()) {
        throw new IllegalArgumentException();
    }
}

Matcher
只会
find()
一次。然后,它可以报告其
开始
位置,您可以使用该位置来
子字符串
原始文件名。

使用此实用程序功能:

public static boolean endsWithIgnoreCase(String str, String suffix)
{
    int suffixLength = suffix.length();
    return str.regionMatches(true, str.length() - suffixLength, suffix, 0, suffixLength);
}
现在您可以执行以下操作:

while (endsWithIgnoreCase(fileName, ".csv")) {
    fileName = fileName.substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV));
    if (fileName.trim().isEmpty()) {
        throw new IllegalArgumentException();
    }
}

将文件名转换为小写形式-
filename。lastIndexOf(…)
也有同样的问题。还必须将其转换为小写。除此之外:这就是答案@除非您需要在文件名中保留大小写,否则这就是答案。@ThomasStets With
fileName.toLowerCase().lastIndexOf(file\u SUFFIX\u CSV)
您没有更改变量。您只是在更改索引的计算。变量
fileName
仍然被原始字符串的子字符串(
fileName.substring(…)
)替换。@ThomasStets:事实上,这个答案不会破坏fileName变量,因为字符串是不可变的。答案是1+。
public static boolean endsWithIgnoreCase(String str, String suffix)
{
    int suffixLength = suffix.length();
    return str.regionMatches(true, str.length() - suffixLength, suffix, 0, suffixLength);
}
while (endsWithIgnoreCase(fileName, ".csv")) {
    fileName = fileName.substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV));
    if (fileName.trim().isEmpty()) {
        throw new IllegalArgumentException();
    }
}