Need to get a string after a "word" in a string in c#

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 is

"Error description, code : -1"

so i have to find the word code in the above string and i have to get the error code. I have seen regex but now clearly understood. Is there any simple way ?


Solution 1:

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
}

Solution 2:

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.

Solution 3:

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

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

Solution 4:

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

Solution 5:

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);
}