简体   繁体   中英

string split to string array

I have a string variable Result that contains a string like:

"<field1>text</field1><field2>text</field2> etc.."

I use this code to try to split it:

Result = Result.replace("><", ">|<");

String[] Fields = Result.split("|");

According to the many websites, including this one, this should give me an array like this:

Fields[0] = "<field1>text</field2>"
Fields[1] = "<field2>test</field2>"
etc...

But it gives me an array like:

Fields(0) = ""
Fields(1) = "<"
Fields(2) = "f"
Fields(3) = "i"
Fields(4) = "e"
etc..

So, what am I doing wrong?

Try doing

String[] fields = result.split("\\|");

Note that I've used more conventional variable names (they shouldn't start with capital letters).

Remember that the split methods takes a regular expression as an argument, and | has a specific meaning in the world of regular expressions, which is why you're not receiving what you were expecting.


Relevant documentation:

Your call to split("|") is parsing | as a regular-expression-or, which on its own will split between every character.

You can regex-escape the character to prevent this from occurring, or use a different temporary split character altogether.

String[] fields = result.split("\\|");

or

result = result.replace("><", ">~<");
String[] fields = result.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