darko
darko

Reputation: 793

How to split string between different chars

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?

Upvotes: 12

Views: 28131

Answers (8)

Ryan
Ryan

Reputation: 337

I would just use string.Split twice. Get the string to the right of the first separator. Then, using the result, get the string to the left of second separator.

string text = "the dog :is very# cute"; 
string result = text.Split(":")[1] // is very# cute";
                    .Split("#")[0]; // is very

It avoids playing around with indexes and regex which makes it more readable IMO.

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98750

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.

Upvotes: 19

Oded
Oded

Reputation: 499002

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.

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460108

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);

Upvotes: 1

bas
bas

Reputation: 14912

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]);
    }

Upvotes: 1

user1968030
user1968030

Reputation:

use this code

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

Upvotes: 5

Guffa
Guffa

Reputation: 700342

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);

Upvotes: 8

Denis
Denis

Reputation: 6082

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

Upvotes: 2

Related Questions