简体   繁体   English

在java中按字符串拆分字符串

[英]Split string by char in java

I'm getting a string from the web looking like this: 我从网上得到一个字符串,如下所示:

Latest Episode@04x22^Killing Your Number^May/15/2009

Then I need to store 04x22 , Killing Your Number and May/15/2009 in diffent variables, but it won't work. 然后我需要在不同的变量中存储04x22Killing Your NumberMay/15/2009 04x22 ,但它不起作用。

String[] all = inputLine.split("@");
String[] need = all[1].split("^");
show.setNextNr(need[0]);
show.setNextTitle(need[1]);
show.setNextDate(need[2]);

Now it only stores NextNr , with the whole string 现在它只存储NextNr ,整个字符串

04x22^Killing Your Number^May/15/2009

What is wrong? 怎么了?

String.split(String regex)

The argument is a regualr expression, and ^ has a special meaning there; 参数是一个regualr表达式, ^具有特殊含义; "anchor to beginning" “锚定到开始”

You need to do: 你需要这样做:

String[] need = all[1].split("\\\\^");

By escaping the ^ you're saying "I mean the character '^' " 逃避^你说的是“我的意思是'^'”

如果您有分隔符但不知道它是否包含特殊字符,则可以使用以下方法

String[] parts = Pattern.compile(separator, Pattern.LITERAL).split(text);

Using guava, you can do it elegantly AND fast: 使用番石榴,你可以优雅而快速地做到:

private static final Splitter RECORD_SPLITTER = Splitter.on(CharMatcher.anyOf("@^")).trimResults().omitEmptyStrings();

...

Iterator<String> splitLine = Iterables.skip(RECORD_SPLITTER.split(inputLine), 1).iterator();

show.setNextNr(splitLine.next());
show.setNextTitle(splitLine.next());
show.setNextDate(splitLine.next());
public static String[] split(String string, char separator) {
    int count = 1;
    for (int index = 0; index < string.length(); index++)
        if (string.charAt(index) == separator)
            count++;
    String parts[] = new String[count];
    int partIndex = 0;
    int startIndex = 0;
    for (int index = 0; index < string.length(); index++)
        if (string.charAt(index) == separator) {
            parts[partIndex++] = string.substring(startIndex, index);
            startIndex = index + 1;
        }
    parts[partIndex++] = string.substring(startIndex);
    return parts;
}
String input = "Latest Episode@04x22^Killing Your Number^May/15/2009";

//split will work for both @ and ^
String splitArr[] = input.split("[@\\^]");

/*The output will be,
 [Latest Episode, 04x22, Killing Your Number, May/15/2009]
*/
System.out.println(Arrays.asList(splitArr));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM