How to split string by string delimiter? Unexpected String.Split(“”.ToCharArray()) behavior

How to split string by string delimiter? Unexpected String.Split(“<br>”.ToCharArray()) behavior



I have input string like this (pasted from .NET debugger):


"g: 17.00 2D nap<br>ng: 14.30 2D dub ; 17.15 3D nap<br>ng: 14.30 3D dub ; 17.15 2D nap<br>ng: 17.00 2D dub<br>ng: 17.00 3D dub"



I'm trying to split it by "<br>":


"<br>"


var items = mystring.Split("<br>".ToCharArray()); // 7 elements



I'm getting 7 list elements instead of 5.



It looks like Split function splits also by ";" separator.


Split



For now I found workaround like this:


var items = mystring.Replace("<br>", "|").Split("|".ToCharArray()); // 5 elements



but what is going on?





You are splitting by chars found in <br>, not a complete <br> string. Try regex.split instead.
– Cetin Basoz
Sep 3 at 22:34




2 Answers
2



Your issue is in the use of ToCharArray().


ToCharArray()



The String.Split() overload that takes a char, which you're using, will use each individual character as a delimiter: therefore, by passing in "<br>".ToCharArray(), which gives the constituent characters of <br>, you're splitting your string by any of <, b, r or >, which you'll agree is not what you want.


String.Split()


char


"<br>".ToCharArray()


<br>


<


b


r


>



Now, there isn't an overload for splitting by a single string with no options, but it's pretty easy to circumvent this:


var items = mystring.Split(new "<br>" , StringSplitOptions.None);



Try using RegEx.Split


RegEx.Split


var items = RegEx.Split(mystring, "<br>");



This will split on exact matches of <br> and not split on the characters individually as said in other answers.


<br>



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế