C# 需要在“a”之后获取字符串;字;用c写的字符串#

C# 需要在“a”之后获取字符串;字;用c写的字符串#,c#,string,substring,C#,String,Substring,我有一个c#中的字符串,我必须在字符串中找到一个特定的单词“code”,并且必须得到单词“code”后的剩余字符串 字符串是 错误描述,代码:-1 因此,我必须在上面的字符串中找到单词code,并获得错误代码。 我见过regex,但现在已经明白了。有什么简单的方法吗 string toBeSearched = "code : "; string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Leng

我有一个c#中的字符串,我必须在字符串中找到一个特定的单词“code”,并且必须得到单词“code”后的剩余字符串

字符串是

错误描述,代码:-1

因此,我必须在上面的字符串中找到单词code,并获得错误代码。 我见过regex,但现在已经明白了。有什么简单的方法吗

string toBeSearched = "code : ";
string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Length);
像这样的

也许您应该处理缺少
代码:
的情况

string toBeSearched = "code : ";
int ix = myString.IndexOf(toBeSearched);

if (ix != -1) 
{
    string code = myString.Substring(ix + toBeSearched.Length);
    // do something here
}
您可以调整要拆分的字符串-如果使用
“code:”
,则返回数组的第二个成员(
[1]
)将包含
“-1”
,使用您的示例。

使用
indexOf()
函数

string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
  //DO YOUR LOGIC
  string errorCode = s.Substring(index+4);
}
更简单的方法(如果您的唯一关键字是“code”)可能是:


将此代码添加到项目中

  public static class Extension {
        public static string TextAfter(this string value ,string search) {
            return  value.Substring(value.IndexOf(search) + search.Length);
        }
  }
然后使用

"code : string text ".TextAfter(":")

如果
code
在上述字符串中出现两次,会发生什么情况?您能澄清一下吗?正则表达式有什么问题吗?你试过什么?你现在有什么代码?@LukeHennerley代码可能会出现两次或两次以上,但最后,错误代码定义将是代码:错误代码拆分只接受
params[]char
,不接受
params[]string
:)@LukeHennerley-我的意思是说这不编译:P我坚持更正@LukeHennerley-最简单的重载只接受
params char[]
。所有的
string[]
重载都需要额外的参数。@LukeHennerley初始化字符串数组是非常常见的方法
string originalSting = "This is my string";
string texttobesearched = "my";
string dataAfterTextTobeSearch= finalCommand.Split(new string[] { texttobesearched     }, StringSplitOptions.None).Last();
if(dataAfterTextobeSearch!=originalSting)
{
    //your action here if data is found
}
else
{
    //action if the data being searched was not found
}
string founded = FindStringTakeX("UID:   994zxfa6q", "UID:", 9);


string FindStringTakeX(string strValue,string findKey,int take,bool ignoreWhiteSpace = true)
    {
        int index = strValue.IndexOf(findKey) + findKey.Length;

        if (index >= 0)
        {
            if (ignoreWhiteSpace)
            {
                while (strValue[index].ToString() == " ")
                {
                    index++;
                }
            }

            if(strValue.Length >= index + take)
            {
                string result = strValue.Substring(index, take);

                return result;
            }


        }

        return string.Empty;
    }
  public static class Extension {
        public static string TextAfter(this string value ,string search) {
            return  value.Substring(value.IndexOf(search) + search.Length);
        }
  }
"code : string text ".TextAfter(":")