57

私はc#に文字列を持っていますが、その文字列から特定の単語「code」を見つけ、単語「code」の後に残りの文字列を取得する必要があります。

文字列は

"エラーの説明、コード:-1"

したがって、上記の文字列で単語コードを見つける必要があり、エラーコードを取得する必要があります。私は正規表現を見てきましたが、今でははっきりと理解しています。簡単な方法はありますか?

4

7 に答える 7

118
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
}
于 2013-02-21T09:27:41.217 に答える
20
var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
// code = " : -1"

文字列を微調整して分割することができます-を使用すると、例を使用して"code : "、返される配列([1])の2番目のメンバーにが含まれ"-1"ます。

于 2013-02-21T09:28:11.277 に答える
14

より簡単な方法(唯一のキーワードが「コード」の場合)は次のようになります。

string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();
于 2013-02-21T09:29:37.500 に答える
6

このコードをプロジェクトに追加します

  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(":")
于 2018-12-31T20:12:24.187 に答える
2

使用indexOf()機能

string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
  //DO YOUR LOGIC
  string errorCode = s.Substring(index+4);
}
于 2013-02-21T09:29:01.127 に答える
1
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;
    }
于 2018-12-15T23:28:50.503 に答える
0
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
}
于 2018-10-07T02:12:51.313 に答える