-2

我一直在尝试按字符拆分字符串并将每个拆分值存储在数组中。在 C# 中,它可以通过在 Split() 之后调用 .ToArray() 方法来完成,但这种方法显然不会在 Java 中退出。所以我一直在尝试这样做(rs 是一个字符串列表,其中元素用# 分隔):

    String t[] = new String[10];
    for (int i = 0; i < rs.size(); i++) {
        t = null;
        t = rs.get(i).split("#");
    }

但是整个分割线被传递给数组的索引,如:

String x = "Hello#World"  -> t[0] = "Hello World" (The string is split in one line, so the array will have only one index of 0)

我的问题是如何将每个吐出元素存储在数组的索引中,例如:

t[0] = "Hello"
t[1] = "World"
4

4 回答 4

1

听起来您试图遍历列表,拆分它们然后将数组添加在一起?您定义为 .split 方法的问题正是 split 方法的作用。

    ArrayList<String> rs = new ArrayList<>();
    rs.add("Hello#World");
    rs.add("Foo#Bar#Beckom");

    String [] t = new String[0];
    for(int i=0;i<rs.size();i++) {
        String [] newT = rs.get(i).split("#");
        String [] result = new String[newT.length+t.length];
        System.arraycopy(t, 0, result, 0,  t.length);
        System.arraycopy(newT, 0, result, t.length, newT.length);
        t = result;
    }

    for(int i=0;i<t.length;i++) {
        System.out.println(t[i]);
    }

工作只是发现输出是:

Hello
World
Foo
Bar
Beckom
于 2013-09-14T22:10:56.427 回答
1
public class Test {
public static void main(String[] args) {
    String hw = "Hello#World";

    String[] splitHW = hw.split("#");

    for(String s: splitHW){
        System.out.println(s);
    }
}
}

这为我产生了以下输出:

Hello
World
于 2013-09-14T22:20:33.727 回答
1

试试这个方法:

String string = "Hello#World"
String[] parts = string.split("#");
String part1 = parts[0]; // Hello
String part2 = parts[1]; // World

如果字符串包含#(在这种情况下),最好事先测试一下,只需使用String#contains()

if (string.contains("#")) {
    // Split it.
} else {
    throw new IllegalArgumentException(message);
}
于 2013-09-14T22:06:30.550 回答
0

当问题已经在java中解决时,你为什么要使用循环..试试这个

String x = "Hello#World";
String[] array = x.split("#", -1);

System.out.println(array[0]+" "+array[1]);
于 2013-09-14T22:02:19.500 回答