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.
You can get a range of characters(substring) by using the slice function. Python slice() function returns a slice object that can use used to slice strings, lists, tuples. You have to Specify the parameters- start index and the end index, separated by a colon, to return a part of the string.
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With