需要在“;单词“;在c#中的字符串中

本文关键字:字符串 单词 | 更新日期: 2023-09-27 18:00:25

我在c#中有一个字符串,我必须在该字符串中找到一个特定的单词"code",并获得单词"code"之后的剩余字符串。

字符串是

"错误描述,代码:-1"

所以我必须在上面的字符串中找到单词code,并且我必须得到错误代码。我看过regex,但现在已经清楚地理解了。有什么简单的方法吗?

需要在“;单词“;在c#中的字符串中

string toBeSearched = "code : ";
string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Length);

像这样的东西?

也许你应该处理丢失code :的情况。。。

string toBeSearched = "code : ";
int ix = myString.IndexOf(toBeSearched);
if (ix != -1) 
{
    string code = myString.Substring(ix + toBeSearched.Length);
    // do something here
}
var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
// code = " : -1"

您可以调整字符串以拆分为-如果使用"code : ",则使用您的示例,返回数组的第二个成员([1])将包含"-1"

更简单的方法(如果您唯一的关键字是"code")可能是:

string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();

将此代码添加到您的项目中

  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(":")

使用indexOf()函数

string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
  //DO YOUR LOGIC
  string errorCode = s.Substring(index+4);
}
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;
    }
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
}