Sebastian
Sebastian

Reputation: 4811

Split a string and keep separator string in c#

How can I split a string based on a string and have the resulting array contain the separators as well?

Example:

If my string = "Hello how are you.Are you fine?.How old are you?"

And I want to split based on string "you", then result I want is an array with items { "Hello how are", "you", ".Are", "you", "fine?.How old are", "you", "?" }.

How can I get a result like this? I tried String.Split and

string[] substrings = Regex.Split(source, stringSeparators);

But both are giving the result array without the occurrence of you in it.

Also, I want to split only on the whole word you. I don't want to split if you is a part of some other words. For example, in the case Hello you are so young, I want the result as { "Hello", "you", "so young" }. I don't want to split the word young to { "you", "ng" }.

Upvotes: 0

Views: 197

Answers (4)

dognose
dognose

Reputation: 20889

You can put the seperator into a match group, then it will be part of the result array:

string[] substrings = System.Text.RegularExpressions.Regex.Split(source, "(you)");

Output would be :

"Hello how are ", 
"you" ,
".Are ",
"you",
" fine?.How old are ",
"you",
"?"

Update regarding your additional question: Use word-boundaries around the keyword:

Split(source, "\\b(you)\\b");

Upvotes: 4

praveen.upadhyay
praveen.upadhyay

Reputation: 273

string[] substrings = System.Text.RegularExpressions.Regex.Split(source,"\s* you\s*");

This should work. Below is the output.

"Hello how are"

".Are"

"fine?.How old are"

"?"

Upvotes: 0

vks
vks

Reputation: 67968

\b(you)\b

Split by this and you have your result.

Upvotes: 1

aelor
aelor

Reputation: 11116

regex replace :

(you) with |\1|

now you will have a string like this :

Hello how are |you|.Are |you| fine?.How old are |you|?

now you can simply split on |

Hope that helps

Upvotes: 0

Related Questions