How to split a string between different characters

I am having a problem breaking a line.

I want to split only words between two different characters. I have this text:

string text = "the dog :is very# cute" ; 

How can I get only the words: "very" using the characters (: #).

+8
string split c #
source share
7 answers

You can use String.Split() method params char[] ;

Returns an array of strings containing substrings in this instance that are limited to elements of the 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 the DEMO .

You can use it for any quantity.

+9
source share

This is not quite a split, so using Split will create a bunch of lines that you don't want to use. Just enter the character index and use SubString :

 int startIndex = text.IndexOf(':'); int endIndex = test.IndexOf('#', startIndex); string very = text.SubString(startIndex, endIndex - startIndex - 1); 
+10
source share

use this code

 var varable = text.Split(':', '#')[1]; 
+4
source share

One of the overloads string.Split accepts params char[] - you can use any number of characters to separate:

 string isVery = text.Split(':', '#')[1]; 

Note that I use this overload and take the second element from the returned array.

However, as @Guffa noted in his answer , what you are doing is not really a section, but it extracts a specific substring, so using his approach might be better.

+3
source share
 Regex regex = new Regex(":(.+?)#"); Console.WriteLine(regex.Match("the dog :is very# cute").Groups[1].Value); 
+2
source share

Does it 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]); } 
+2
source share

Use String.IndexOf and String.Substring

 string text = "the dog :is very# cute" ; int colon = text.IndexOf(':') + 1; int hash = text.IndexOf('#', colon); string result = text.Substring(colon , hash - colon); 
+2
source share

All Articles