How to split string between different chars
Solution 1
You can use String.Split()
method with params char[]
;
Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array.
string text = "the dog :is very# cute";
string str = text.Split(':', '#')[1]; // [1] means it selects second part of your what you split parts of your string. (Zero based)
Console.WriteLine(str);
Here is a DEMO
.
You can use it any number of you want.
Solution 2
That's not really a split at all, so using Split
would create a bunch of strings that you don't want to use. Simply get the index of the characters, and use SubString
:
int startIndex = text.IndexOf(':');
int endIndex = test.IndexOf('#', startIndex);
string very = text.SubString(startIndex, endIndex - startIndex - 1);
Solution 3
Regex regex = new Regex(":(.+?)#");
Console.WriteLine(regex.Match("the dog :is very# cute").Groups[1].Value);
Solution 4
One of the overloads of string.Split
takes a params char[]
- you can use any number of characters to split on:
string isVery = text.Split(':', '#')[1];
Note that I am using that overload and am taking the second item from the returned array.
However, as @Guffa noted in his answer, what you are doing is not really a split, but extracting a specific sub string, so using his approach may be better.
Solution 5
Does this help:
[Test]
public void split()
{
string text = "the dog :is very# cute" ;
// how can i grab only the words:"is very" using the (: #) chars.
var actual = text.Split(new [] {':', '#'});
Assert.AreEqual("is very", actual[1]);
}
darko
Updated on July 09, 2022Comments
-
darko almost 2 years
I am having trouble splitting a string. I want to split only the words between 2 different chars:
string text = "the dog :is very# cute";
How can I grab only the words, is very, between the
:
and#
chars? -
Guffa over 11 yearsNote: This will also catch strings between characters that are not in the order specified in the question, for example
is
in"This #is# a :test#."