Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的字符串解析异常行为_Java_String_Parsing - Fatal编程技术网

java中的字符串解析异常行为

java中的字符串解析异常行为,java,string,parsing,Java,String,Parsing,由于某种原因,当我使用“|”解析字符串时,这种解析技术不起作用。 我的java代码如下所示 public class Testing{ public static void main(String[] args){ String sentence = "SA|2|What is the capital of Italy|Rome"; System.out.println(sentence); System.out.println("----

由于某种原因,当我使用
“|”
解析字符串时,这种解析技术不起作用。 我的java代码如下所示

public class Testing{
    public static void main(String[] args){
        String sentence = "SA|2|What is the capital of Italy|Rome";
        System.out.println(sentence);
        System.out.println("---------------------------");

        String[] tokens = sentence.split("|");
        for(String word: tokens)
            System.out.println(word);
    }
}
SA|2|What is the capital of Italy|Rome
---------------------------
SA
2
What is the capital of Italy
Rome
出于某种原因,我的输出看起来像这样

SA|2|What is the capital of Italy|Rome
---------------------------
S
A
|
2
|
W
h
a
t

i
s

t
h
e

c
a
p
i
t
a
l
...(and so on)
我想要它做的是像这样显示整个字符串,而不是像这样显示它给我的内容

public class Testing{
    public static void main(String[] args){
        String sentence = "SA|2|What is the capital of Italy|Rome";
        System.out.println(sentence);
        System.out.println("---------------------------");

        String[] tokens = sentence.split("|");
        for(String word: tokens)
            System.out.println(word);
    }
}
SA|2|What is the capital of Italy|Rome
---------------------------
SA
2
What is the capital of Italy
Rome

有人知道为什么它会导致每行打印每个字母,而不是每一个单词都打印吗?

请参考下面的答案

你需要说
句子.split(\\\\\;)原因是,正如我在评论中提到的,|是OR的符号。所以,假设你想在一个点或一个空白处分割一些东西,你会说句子

使用上面的代码。对于特殊字符,需要转义语法。因此,在特殊字符之前使用\\。

将拆分更改为

final String[] tokens = sentence.split("\\|");

这是您的工作。

|代表或当您进行拆分时。试着通过做一些类似于“\\\\\”的事情来逃避它,事实上,我从来不用在一个|字符串[]tokens=句子上拆分任何东西;使用\\表示特殊字符。我尝试了(“\\\\\”)并成功了!非常感谢。如果你把它作为一个问题发布,我可以把它标记为正确答案!我贴了一个答案,如果你愿意,你可以投上去。提示:当你已经知道它是重复的;你为什么不这样结束投票?嗯,说得好,说实话,我不知道怎么做。我想我也可以在评论中快速回答它,并作为OP>提示的一个答案:只有代码而没有解释的答案只是。。。不好的。