简体   繁体   English

拆分此字符串,我的代码有什么问题?

[英]splitting this string, whats wrong with my code?

This is a beginner course so there is probably an easier method, but can someone look at my code and tell me why it wont split the last string and print it? 这是一门初学者课程,所以可能有一个更简单的方法,但是有人可以看一下我的代码,然后告诉我为什么它不会拆分最后一个字符串并打印出来吗? I split it successfully the first two times. 我成功地将它拆分了两次。

//////////////////////////////////// String line = "user=Abby&topic=0&message=I+cannot+wait+for+the+snow."; /////////////////////////////////字符串行=“ user = Abby&topic = 0&message = I + cannot +等待+为在+雪“。

    String[] parts = line.split("&"); //split&
    String part1 = parts[0]; // user=Abby 
    String part2 = parts[1];//  topic=0
    String part3 = parts[2];//  message=I+cannotwaitforthesnow

    String[] user = part1.split("=");  //Split USER=Abby
    String user1 = user[0]; // user
    String user2 = user[1]; //  Abby

    String[] topic = part2.split("=");  //split topi=0
    String topic1 = topic[0]; // Topic
    String topic2 = topic[1]; // 0

    String[] text = part3.split("="); //split message=iasd
    String text1 = text[0]; // message
    String text2 = text[1]; // I+cannot+wait+for+the+snow


    String[] message = text2.split("+"); //split I+cannot+wait+for+the+snow.
    String message1 = message[0];//I
    String message2 = message[1];//cannot
    String message3 = message[2];//wait
    String message4 = message[3];//for
    String message5 = message[4];//the
    String message6 = message[5];//snow.


    output.println("This is the input that the client sent: ");

    System.out.println(user2);
    System.out.println(topic1 + topic2);
    System.out.println(message1 + message2 + message3 + message4 + message5 + message6);

////////////////////// //////////////////////

so it successfully works, but when i added the split for message at the end it did not split and print, just blank. 因此它可以成功工作,但是当我在消息末尾添加拆分消息时,它没有拆分并打印,只是空白。 an anyone tell me why? 有人告诉我为什么吗?

thanks for any help 谢谢你的帮助

The Javadocs say Javadocs说

public String[] split(String regex) public String [] split(String regex)

Splits this string around matches of the given regular expression. 围绕给定正则表达式的匹配项拆分此字符串。

And + is a reserved character in regex so you need to escape it. +是正则表达式中的保留字符,因此您需要对其进行转义。

You should try 你应该试试

String[] message = text2.split("\\+");

In java '+' is a reserved character, you should escape it with '\\' in order to use it in this context 在Java中,“ +”是保留字符,为了在此上下文中使用它,应使用“ \\”对其进行转义

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

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