Raspi Surya Raspi Surya - 2 months ago 12
C# Question

Split a sentence using multiple characters?

I have an input box to input sentences, and I want to split it at every specific character. I have done this for

.
:

var ArraySourceTexts = textbox.Text.Split(new Char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);


My question is, what if I have multiple character? for example I want it split if the sentences contains the characters:
.
,
?
,
!
.

Please share!

Answer Source

Using string.Split with a Char array, you can specify as many characters as you want within that array. Just add more characters which will cause the split:

char[] splitChars = new char[] { '.', '!', '?', ',' };
var ArraySourceTexts = textbox.Text.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);

Input:

this is an example. Please check, and let me know your thoughts!

Output:

[0] this is an example 
[1] Please check 
[2] and let me know your thoughts   

Method 2: If you want to split the string but keep the seperators (like you mentioned in the comments):

string[] arr = Regex.Split(textbox.Text, @"(?<=[.,!?])");

Input:

this is an example. Please check, and let me know your thoughts!

Output:

[0] this is an example.
[1] Please check, 
[2] and let me know your thoughts!