Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract range of characters from a string

Tags:

string

c#

.net

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.

like image 573
BigBug Avatar asked Feb 04 '12 17:02

BigBug


People also ask

How do you access a range of characters from a string in Python?

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.

How do I extract character from 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.


1 Answers

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.

like image 69
Ondrej Tucny Avatar answered Sep 18 '22 05:09

Ondrej Tucny