简体   繁体   中英

How to split string separated by | character

I have input string in the following format first|second|third|<forth>|<fifth>|$sixth I want to split this string into an array of string with value [first,second,third,,,$sixth]. I am using following code to split the string but that is not working. please help me.

public String[] splitString(String input){
String[] resultArray = input.split("|")
return resultArray;
    }

Could you please tell me what am I doing wrong.

You need to escape | using backslash as it is a special character. This should work:

String[] resultArray = input.split("\\|")

| is a meta character meaning it represents something else in regex. Considering split takes regex as an argument, it interprets the argument using regex. You need to "escape" all of the meta characters by placing a \\\\ before it. In your case, you would do:

String[] resultArray = input.split("\\|");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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