所以我一直在尝试为编程课做这个练习,基本上你必须在空白处分割字符串。
字符串是:4157245.8043 671332.0498 4774713.5642 近似位置 XYZ
我班上的很多人在根据位置定义子字符串时都这样做了,基本上是从 x 到 y 的索引,我不想这样做,因为一旦字符串发生变化,你的整个程序就无法正常工作
现在我的问题是,虽然坐标分离得很好,但后面的文本也被分离成不同的部分,从而使我的输出:
part 1: 4157245.8043
part 2: 671332.0498
part 3: 4774713.5642
part 4: APPROX
part 5: POSITION
part 6: XYZ
在这种情况下,我怎样才能让程序排除字符串的那部分?我想说 id 必须启动一个数组,对出现的每个空间进行计数,但我现在不知道如何实现它,并且已经为此苦苦挣扎了一段时间。
这是我现在的代码:
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+");
//System.out.println("Dieser Satellit befindet sich über [] in der Höhe von []");
for (int i=1; i<s.length(); i++) {
System.out.println("part " + ((i+1)-1) + ": " + rrr[i]);
}
}
提前致谢:D
我尝试实现一个在for循环中计数的数组,但我一定做错了,因为它不能正常工作
您可以检查字符串是否由字母组成,如本问题所述:在不使用正则表达式的情况下,在 Java 中判断字符是字母还是数字的最佳方法是什么?
然后执行此操作,然后将字符串连接到一个字符串,或者您可以在之前检查/获取空格位置并使用子字符串...
您可以使用正则表达式
请注意
Pattern pattern = Pattern.compile(" ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ");
Matcher matcher = pattern.matcher(" 4157245.8043 671332.0498 4774713.5642 APPROX POSITION XYZ ");
if (matcher.matches()) {
String s1 = matcher.group(1); // 4157245.8043
String s2 = matcher.group(2); // 671332.0498
String s3 = matcher.group(3); // 4774713.5642
String s4 = matcher.group(4); // APPROX
String s5 = matcher.group(5); // POSITION
String s6 = matcher.group(6); // XYZ
}