Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve string from the middle of a string

Tags:

string

c#

I have a coded string that I'd like to retrieve a value from. I realize that I can do some string manipulation (IndexOf, LastIndexOf, etc.) to pull out 12_35_55_219 from the below string but I was wondering if there was a cleaner way of doing so.

"AddedProject[12_35_55_219]0"
like image 736
ahsteele Avatar asked Mar 15 '10 18:03

ahsteele


People also ask

How do I extract part of a 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.

How do you pull the middle of a string in Excel?

The Excel MID function extracts a given number of characters from the middle of a supplied text string. For example, =MID("apple",2,3) returns "ppl". The Excel LEN function returns the length of a given text string as the number of characters.


1 Answers

If you can be sure of the format of the string, then several possibilities exist:

My favorite is to create a very simple tokenizer:

string[] arrParts = yourString.Split( "[]".ToCharArray() );

Since there is a regular format to the string, arrParts will have three entries, and the part you're interested in would be arrParts[1].

If the string format varies, then you will have to use other techniques.

like image 102
kmontgom Avatar answered Oct 15 '22 22:10

kmontgom