如何将字符串分割成多个部分?

9
我有一个由空格分隔的字符串,例如“firstword second third”,和一个ArrayList。我想把字符串分成几个片段,并将“piece”字符串添加到ArrayList中。
例如,“firstword second third”可以分为三个单独的字符串,因此ArrayList将有3个元素;“1 2 3 4”可以分为4个字符串,在ArrayList的4个元素中。请参见下面的代码:
public void separateAndAdd(String notseparated) {
    for(int i=0;i<canBeSepartedinto(notseparated);i++{
    //what should i put here in order to split the string via spaces?
        thearray.add(separatedstring);
    }
}

public int canBeSeparatedinto(String string)
    //what do i put here to find out the amount of spaces inside the string? 
    return ....
}

如果您不理解我的意思或者我在这篇文章中有错误的话,请留下评论。感谢您的时间!

7个回答

14
你可以使用 split() 方法按照空格来分割字符串:
String[] parts = inputString.split(" ");
之后遍历该数组,如果!"".equals(parts[i],就将其添加到列表中。

为什么要使用 Integer.parseInt(parts[i]);?原帖并没有要求将分割后的字符串转换为整数。 - Eng.Fouad

5
如果你想按一个空格分割,可以使用.split(" ");。如果要按照一排中的所有空格进行分割,则使用.split(" +");
考虑以下示例:
class SplitTest {
    public static void main(String...args) {
        String s = "This is a  test"; // note two spaces between 'a' and 'test'
        String[] a = s.split(" ");
        String[] b = s.split(" +");
        System.out.println("a: " + a.length);
        for(int i = 0; i < a.length; i++) {
            System.out.println("i " + a[i]);
        }
        System.out.println("b: " + b.length);
        for(int i = 0; i < b.length; i++) {
            System.out.println("i " + b[i]);
        }
    }
}

如果您担心非标准空格,可以使用"\\s+"代替"+",因为"\\s"将捕获任何空白字符,而不仅仅是“空格字符”。

因此,您的separate and add方法变为:

void separateAndAdd(String raw) {
    String[] tokens = raw.split("\\s+");
    theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
    for(String s : tokens) {
        theArray.add(s);
    }

}

这是一个更完整的例子 - 请注意,在测试期间我发现了separateAndAdd方法中的一个小修改。
import java.util.*;
class SplitTest {
    public static void main(String...args) {
        SplitTest st = new SplitTest();
        st.separateAndAdd("This is a test");
        st.separateAndAdd("of the emergency");
        st.separateAndAdd("");
        st.separateAndAdd("broadcast system.");

        System.out.println(st);
    }

    ArrayList<String> theArray = new ArrayList<String>();

    void separateAndAdd(String raw) {
        String[] tokens = raw.split("\\s+");
        theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
        for(String s : tokens) {
            if(!s.isEmpty()) theArray.add(s);
        }
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for(String s : theArray)
            sb.append(s).append(" ");
        return sb.toString().trim();
    }
}

请再次阅读这部分内容:“已添加4次到ArrayList中。” - Dan D.
丹,我不确定你在哪里看到它们被加在一起了。 - corsiKa
1
谢谢,我认为这可能是答案,但我必须尝试所有这些。 - Ewen
for(String s : tokens) sum += Integer.parseInt(s);对于tokens中的每个字符串s,将其转换为整数并累加到sum中。 - Dan D.
@Dan,那个已经在你评论之前被移除了,并被更合适的解决方案所替代。 - corsiKa
显示剩余3条评论

3
我建议使用apache.commons.lang.StringUtils库。它是最简单的,并且涵盖了您可以想要的所有不同条件,以最少的代码拆分字符串。
这里是split方法的参考: Split Method 您还可以在同一链接上查看split方法的其他选项。

2
如果您想将字符串分成不同的部分,比如我现在要展示的是如何将这个字符串14-03-2016按照日、月和年进行分割。
 String[] parts = myDate.split("-");
           day=parts[0];
           month=parts[1];
           year=parts[2];

2

请执行以下操作:

thearray = new ArrayList<String>(Arrays.asList(notseparated.split(" ")));

或者如果thearray已经被实例化

thearray.addAll(Arrays.asList(notseparated.split(" ")));

1
您可以使用.split()来做到这一点,请尝试。
String[] words= inputString.split("\\s");

0
尝试这个: 将字符串分成两部分:
public String[] get(String s){
    int l = s.length();
    int t = l / 2;
    String first = "";
    String sec = "";
    for(int i =0; i<l; i++){
        if(i < t){
            first += s.charAt(i);
        }else{
            sec += s.charAt(i);
        }
    }
    String[] result = {first, sec};
    return result;
}

例子:

String s = "HelloWorld";
String[] res = get(s);
System.out.println(res[0]+" "+res[1])

输出:

Hello World

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接