- Home /
How to extract part of a string variable?
I have a string variable in C# in the follow format:
part1/part2/variable1/variable2/variable3
The "parts" of the string are always the same, however the "variables" change and so I have no way of knowing in advance what they will be. What I need is to be able to extract "variable1" only and store this in another string variable. I have tried using string split and trim, but because I don't know how many characters long any of the "variables" will be, I'm not sure how far after the end of "part2" I should ignore/remove the rest of the string.
Any suggestions how to do this?
@Prefab Just concatenate a character which will not be part of your string variable. e.g
Part1/part2/"$XYZ$/ABC/"
Note: "$XYZ$" is vairable1and "ABC" is variable3.
I hope you got my idea.
Sorry not sure I understand. How can I concatenate if I don't know what variable1 will be?
string.Split( '/' ) doesn't work? I think it doesn't need the length of characters.
Do you mean splitting the string into an array of strings and then making the 3rd array item equal to variable1? Trying this now...
Answer by 5c4r3cr0w · May 12, 2016 at 06:05 AM
String.Split() returns the array of the string so If you use String.Split("/") , it'll split the entire string into seaprate strings before and after the character "/".
For example you have string "Variable1/Variable2". if you use "Variable1/Variable2".Split("/"), you'll have two different string "Variable1" and "Variable2" but you have to store it in array of the string like
string[] x = "Variable1/Variable2".split('/');
So you'll have x[0] = "Variable1" and x[1] = "Variable2";.
Now in your case I don't see any need to know how long any string should be as you want to seaprately store the variable1. So Split() is the best option for you.
Hope it helped.