Search code examples
c#.netstring

How to extract range of characters from a string


If I have a string such as the following:

 String myString = "SET(someRandomName, \"hi\", u)"; 

where I know that "SET(" will always exists in the string, but the length of "someRandomName" is unknown, how would I go about deleting all the characters from "(" to the first instance of """? So to re-iterate, I would like to delete this substring: "SET(someRandomName, \"" from myString.

How would I do this in C#.Net?

EDIT: I don't want to use regex for this.


Solution

  • Providing the string will always have this structure, the easiest is to use String.IndexOf() to look-up the index of the first occurence of ". String.Substring() then gives you appropriate portion of the original string.

    Likewise you can use String.LastIndexOf() to find the index of the first " from the end of the string. Then you will be able to extract just the value of the second argument ("hi" in your sample).

    You will end up with something like this:

    int begin = myString.IndexOf('"');
    int end = myString.LastIndexOf('"');
    string secondArg = myString.Substring(begin, end - begin + 1);
    

    This will yield "\"hi\"" in secondArg.

    UPDATE: To remove a portion of the string, use the String.Remove() method:

    int begin = myString.IndexOf('(');
    int end = myString.IndexOf('"');
    string altered = myString.Remove(begin + 1, end - begin - 1);
    

    This will yield "SET(\"hi\", u)" in altered.