What if I want to split a string using a delimiter that is a word?
For example, This is a sentence
.
I want to split on is
and get This
and a sentence
.
In Java
, I can send in a string as a delimiter, but how do I accomplish this in C#
?
What if I want to split a string using a delimiter that is a word?
For example, This is a sentence
.
I want to split on is
and get This
and a sentence
.
In Java
, I can send in a string as a delimiter, but how do I accomplish this in C#
?
You can use String.Replace() to replace your desired split string with a character that does not occur in the string and then use String.Split on that character to split the resultant string for the same effect.
EDIT: The "is" is padded on both sides with spaces in the array in order to preserve the fact that you only want the word "is" removed from the sentence and the word "this" to remain intact.
Here is an extension function to do the split with a string separator:
Example of usage:
You can use the Regex.Split method, something like this:
Edit: This satisfies the example you gave. Note that an ordinary String.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
Example from the docs:
Based on existing responses on this post, this simplify the implementation :)