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?
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With