繁体   English   中英

如何在不同字符之间拆分字符串

[英]How to split string between different chars

我在拆分字符串时遇到问题。 我只想在 2 个不同的字符之间拆分单词:

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

我怎样才能只抓取:#字符之间的单词, is very

您可以将String.Split()方法与params char[]

返回一个字符串数组,其中包含此实例中由指定 Unicode 字符数组的元素分隔的子字符串。

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

这是一个DEMO

您可以随意使用它。

这根本不是真正的拆分,因此使用Split会创建一堆您不想使用的字符串。 只需获取字符的索引,然后使用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);

string.Split重载之一采用params char[] - 您可以使用任意数量的字符进行拆分:

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

请注意,我正在使用该重载并从返回的数组中获取第二项。

但是,正如@Guffa 在他的回答中指出的那样,您所做的并不是真正的拆分,而是提取特定的子字符串,因此使用他的方法可能会更好。

这是否有帮助:

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

使用String.IndexOfString.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);

我只会使用string.Split两次。 获取第一个分隔符右侧的字符串。 然后,使用结果,获取第二个分隔符左侧的字符串。

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

它避免使用索引和正则表达式,这使其在 IMO 中更具可读性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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