简体   繁体   中英

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?

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

使用此代码

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

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM