Click here to Skip to main content
15,899,679 members
Please Sign up or sign in to vote.
4.56/5 (5 votes)
See more:
Dear All,

I have ListView full of things, but basically all the items have the same format :

TY223 [16]
TW121 [223]
...
...

If I want to substract the value 16 and TY223 from TY223 [16] , I go about it like this :
C#
string[] a = itm.Value.ToString().Split('[');
string[] b = a[1].ToString().Split(']');
string first = a[1].ToString().Trim();
string second = b[0].ToString().Trim();

This works fine, however I'm only after the value 16. Is there a more elegant way of extracting this value from the item, instead of using Split?

Kind regards,

[Corrected some code formatting]
Posted
Updated 3-Mar-10 23:19pm
v2

Hi,

I like using regex:

System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"[ [\]]");<br />label1.Text = "";<br />foreach (String s in r.Split(textBox2.Text))<br />{<br />  label1.Text += s + "\n";<br />}


You might use index 0 and 2 and you don't need .Trim() again. ;-)


Have fun
 
Share this answer
 
You might be able to do something like (I'd normally use something like this for reading from a file, but it seems to work here too):

string ReadWord(string buffer, char delimiter, int startPos)<br />{<br />    StringBuilder sb = new StringBuilder();<br />    for(int i=startPos; i<buffer.Length; i++)<br />    {<br />        if(buffer[i] == delimiter)<br />            break;<br /><br />        sb.append(buffer[i]);<br />    }<br /><br />    return sb.toString();<br />}<br /><br />void main()<br />{<br />    string firstPart = ReadWord(fullLine, ' ', 0);<br />    int startPos = fullLine.IndexOf('[');<br />    string secondPart = ReadWord(fullLine, ']', startPos);<br />}


Thats just from memory so it may not compile, but you get the idea.

 
Share this answer
 
How about this shorter one liner?
C#
string Result = inputString.Split('[')[1].Split(']')[0];
 
Share this answer
 
how about, in one line...

string resultString = inputString.Substring(inputString.IndexOf('[') + 1, inputString.IndexOf(']') - inputString.IndexOf('[') - 1);


 
Share this answer
 
Have you considered regular expressions?
 
Share this answer
 
Agree with previous poster, regular exp. is the best :)
 
Share this answer
 
It is great with RegEx, ;P :thumbsup:
I Used it and it worked fine...
Cheers!!!!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900