简体   繁体   English

获取该String C#的一部分

[英]Get a part of that String C#

:barbosza!barbosza@barbosza.tmi.twitch.tv PRIVMSG #pggamesbr :My text

我想要第二个':'之后的部分,但是我不能被':'分割,因为有时也包含它。

You can split and specify the maximum number of items, so that everything after the second colon ends up in the third item: 您可以拆分并指定最大项数,以便第二个冒号之后的所有内容最终出现在第三个项中:

string[] parts = str.Split(new char[]{':'}, 3);

The part after the second colon is now in parts[2] . 现在,第二个冒号之后的部分位于parts[2]

I guess that "he contains it too" means "My text contains it too". 我猜“他也包含它”的意思是“我的文字也包含它”。

In that case, do this 在这种情况下,请执行此操作

string toFind = "#pggamesbr :";
string myText = myString.Substring(myString.IndexOf(toFind) + toFind.Length);

I like Guffa's simple Split solution, and would go with that if this is all you need here. 我喜欢Guffa的简单Split解决方案,如果这是您在这里所需要的,那就可以使用它。 But, just for fun... 但是,只是为了好玩...

If you run into a lot of odd cases like this -- things you wish were easier to do with strings -- you can consider adding extension methods to handle them. 如果遇到很多奇怪的情况-您希望使用字符串更轻松地进行操作-您可以考虑添加扩展方法来处理它们。 Eg, 例如,

using System;

public static MyStringExtentions
{
    public static string After(this string orig, char delimiter)
    {
        int p = orig.indexOf(delimiter);
        if (p == -1)
            return string.Empty;
        else
            return orig.Substring(p + 1);
    }
}

And then, in your existing code, as long as you have a using directive to include reference access to MyStringExtentions 's definition: 然后,在现有代码中,只要您具有using指令即可包括对MyStringExtentions的定义的引用访问权:

string afterPart = myString.After(':').After(':');

Disclaimer: I didn't actually test this. 免责声明:我实际上没有对此进行测试。 Some tuning may be required. 可能需要一些调整。 And it could probably be tuned to be more efficient, etc. 而且可能会调整为更高效等。

Again, this is probably overkill for this one problem. 同样,对于这个问题,这可能是多余的。 (See Guffa's perfectly good simple answer for that.) Just tossing it out for when you find yourself with lots of these and want a common way to make them available. (为此,请参见Guffa的一个非常简单的好答案。)当您发现自己有很多这样的东西并且想要一种通用的方式来使用它们时,就把它扔出去。

Ref. 参考。 Extension Methods (C# Programming Guide) 扩展方法(C#编程指南)

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

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