Need to get a string after a “word” in a string in c#

前端 未结 7 1588
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 13:45

i\'m having a string in c# for which i have to find a specific word \"code\" in the string and have to get the remaining string after the word \"code\".

The string i

相关标签:
7条回答
  • 2020-12-08 13:50
    var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
    // code = " : -1"
    

    You can tweak the string to split by - if you use "code : ", the second member of the returned array ([1]) will contain "-1", using your example.

    0 讨论(0)
  • 2020-12-08 13:51
    string toBeSearched = "code : ";
    string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Length);
    

    Something like this?

    Perhaps you should handle the case of missing code :...

    string toBeSearched = "code : ";
    int ix = myString.IndexOf(toBeSearched);
    
    if (ix != -1) 
    {
        string code = myString.Substring(ix + toBeSearched.Length);
        // do something here
    }
    
    0 讨论(0)
  • 2020-12-08 13:59

    use indexOf() function

    string s = "Error description, code : -1";
    int index = s.indexOf("code");
    if(index != -1)
    {
      //DO YOUR LOGIC
      string errorCode = s.Substring(index+4);
    }
    
    0 讨论(0)
  • 2020-12-08 14:00

    Simpler way (if your only keyword is "code" ) may be:

    string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();
    
    0 讨论(0)
  • 2020-12-08 14:00
    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
    }
    
    0 讨论(0)
  • 2020-12-08 14:04

    add this code to your project

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

    then use

    "code : string text ".TextAfter(":")
    
    0 讨论(0)
提交回复
热议问题