如何在Java中截取字符串至第二个逗号位置

本文介绍如何使用`string.indexof()`和`substring()`精准截取文本行中从开头到第二个逗号(含)的内容,适用于解析csv风格数据、提取前两字段等场景。

在处理结构化文本(如简易CSV格式)时,常需按分隔符提取特定字段。例如,给定一行:
14, "Stanley #2 Philips Screwdriver", true, 6.95
目标是保留开头至第二个逗号(含)的所有字符,即输出:
14, "Stanley #2 Philips Screwdriver",

这无法通过简单 split(",", n) 实现——因为 split() 会破坏原始格式(如引号内逗号被错误切分),且返回数组后拼接易出错;而正则限制(如 limit=3)仅控制分割次数,不满足“截断到第n个分隔符”的语义。

✅ 正确解法是利用 String.indexOf() 的重载方法定位第二个逗号位置:

public static void fileReader() throws FileNotFoundException {
    File file = new File("/Users/14077/Downloads/inventory.txt");
    Scanner scan = new Scanner(file);
    String targetId = "14"; // 注意:原代码中 test="4452" 但示例数据为 "14",请按实际ID调整

    while (scan.hasNextLine()) {
        String line = scan.nextLine().trim();

        // 安全查找第二个逗号:先找第一个,再从其后找第二个
        int firstComma = line.indexOf(',');
        if (firstComma == -1) continue; // 跳过无逗号行

        int secondComma = line.indexOf(',', firstComma + 1);
        if (secondComma == -1) continue; // 跳过少于两个逗号的行

        // 截取 [0, secondComma+1) —— 包含第二个逗号
        String result = line.substring(0, secon

dComma + 1); // 按需匹配ID(注意:itemID[0] 是第一个字段,即逗号前部分) if (result.startsWith(targetId + ",")) { System.out.println(result); } } scan.close(); }

? 关键逻辑说明:

  • line.indexOf(',') → 获取第一个逗号索引;
  • line.indexOf(',', firstComma + 1) → 从第一个逗号之后一位开始搜索,确保找到的是第二个
  • substring(0, secondComma + 1) → 取闭区间 [0, secondComma] 的子串(substring 的结束索引是排他性的,故需 +1)。

⚠️ 注意事项:

  • 必须校验 indexOf() 返回值是否为 -1,避免 StringIndexOutOfBoundsException;
  • 若文件含空行或格式异常(如仅一个逗号),跳过可提升鲁棒性;
  • 此方法不解析引号或转义,适用于简单分隔场景;若需完整CSV解析(如处理 "a,b",c 中引号内逗号),应使用专业库(如 OpenCSV 或 Apache Commons CSV);
  • Scanner 使用后建议显式调用 scan.close() 防止资源泄漏。

? 扩展提示:
如需提取前两个字段(不含第二个逗号),可改为 line.substring(0, secondComma);
如需进一步分割字段,可在截取后对 result 执行 split(",", 2),安全获取 ID 和描述。