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

如何让Java的String.split()在指定位置停止分割?

解决字符串分割后只保留前三个坐标的问题

你的代码存在两个关键问题:

  • 循环条件用了i < s.length(),这是原字符串的长度,远大于分割后数组的长度,会直接触发数组越界异常
  • 数组索引从0开始,你从i=1开始遍历,会跳过第一个坐标,还会读到后面不需要的内容

下面给你几种简单可行的解决方法:

方法1:限制循环次数,只取前三个元素

直接修改循环逻辑,只遍历数组的前3个元素(对应索引0、1、2):

public class test7 {
    public static void main(String[] args) {
        String s = " 4157245.8043 671332.0498 4774713.5642 APPROX POSITION XYZ ";
        String[] rrr = s.split("\\s+");
        
        // 只遍历前3个坐标元素
        for (int i = 0; i < 3; i++) {
            System.out.println("part " + (i + 1) + ": " + rrr[i]);
        }
        
        // 也可以直接单独获取每个坐标用于后续业务
        String xCoord = rrr[0];
        String yCoord = rrr[1];
        String zCoord = rrr[2];
        System.out.println(String.format("卫星坐标:X=%s, Y=%s, Z=%s", xCoord, yCoord, zCoord));
    }
}

方法2:用split的第二个参数限制分割数量

String.split()支持第二个参数,用来指定分割后最多生成的元素数量。传入4的话,会把前三个空格分割为独立元素,剩下的所有内容合并为第四个元素,这样数组长度固定为4,直接取前三个即可:

public class test7 {
    public static void main(String[] args) {
        String s = " 4157245.8043 671332.0498 4774713.5642 APPROX POSITION XYZ ";
        // 第二个参数4表示最多分割成4个部分
        String[] rrr = s.split("\\s+", 4);
        
        // 前三个就是目标坐标
        for (int i = 0; i < 3; i++) {
            System.out.println("part " + (i + 1) + ": " + rrr[i]);
        }
    }
}

方法3:正则匹配直接提取前三个浮点数字

如果想更精准定位坐标,还可以用正则表达式直接匹配出三个浮点数字,避免分割后处理多余内容:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test7 {
    public static void main(String[] args) {
        String s = " 4157245.8043 671332.0498 4774713.5642 APPROX POSITION XYZ ";
        // 匹配带小数点的数字的正则表达式
        Pattern pattern = Pattern.compile("\\d+\\.\\d+");
        Matcher matcher = pattern.matcher(s);
        
        int count = 0;
        // 只提取前三个匹配结果
        while (matcher.find() && count < 3) {
            System.out.println("part " + (count + 1) + ": " + matcher.group());
            count++;
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:25:25