You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过索引位置拆分文件名:将文件名拆分为含主体与后缀的数组

拆分文件名成包含文件名主体和扩展名的数组

既然你已经通过LastIndexOf('.')获取到了最后一个点的索引位置,只需要通过字符串截取就能得到目标数组,以下是常见编程语言的实现示例:

C# 实现

string fileName = "IMG-20190604-WA0005.jpg";
int dotIndex = fileName.LastIndexOf('.');
string[] splitResult = new string[2];

// 处理文件名不含扩展名的情况
if (dotIndex != -1)
{
    splitResult[0] = fileName.Substring(0, dotIndex);
    splitResult[1] = fileName.Substring(dotIndex + 1);
}
else
{
    splitResult[0] = fileName;
    splitResult[1] = string.Empty; // 无扩展名时可设为空字符串或null,按需调整
}

Java 实现

String fileName = "IMG-20190604-WA0005.jpg";
int dotIndex = fileName.lastIndexOf('.');
String[] splitResult = new String[2];

if (dotIndex != -1) {
    splitResult[0] = fileName.substring(0, dotIndex);
    splitResult[1] = fileName.substring(dotIndex + 1);
} else {
    splitResult[0] = fileName;
    splitResult[1] = "";
}

核心逻辑说明

  • 用字符串截取方法从开头到最后一个点的位置,获取文件名主体
  • 从最后一个点的下一位开始截取,得到文件扩展名
  • 增加dotIndex != -1的判断,避免文件名中没有点时出现索引越界异常

内容的提问来源于stack exchange,提问作者Domagoj Hamzic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 10:18:33