Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string between different chars

Tags:

string

c#

split

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?

like image 965
darko Avatar asked Feb 10 '13 12:02

darko


People also ask

Can a string be split on multiple characters?

Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.

How do I split a string into multiple parts?

You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.

How do you split all 4 characters in a string Python?

To split a string every n characters:Import the wrap() method from the textwrap module. Pass the string and the max width of each slice to the method. The wrap() method will split the string into a list with items of max length N.


2 Answers

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.

like image 120
Soner Gönül Avatar answered Oct 24 '22 19:10

Soner Gönül


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);
like image 36
Guffa Avatar answered Oct 24 '22 18:10

Guffa