然后是.Split(']');的更优雅的方式. [英] More elegant way then .Split(']');

查看:89
本文介绍了然后是.Split(']');的更优雅的方式.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,

我的ListView里装满了东西,但是基本上所有的东西都具有相同的格式:

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

如果要从TY223 [16]中减去值16和TY223,则可以这样处理:

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 :

string[] a = itm.Value.ToString().Split('[');
string[] b = a[1].ToString().Split(']');
string first = a[1].ToString().Trim();
string second = b[0].ToString().Trim();


这很好用,但是我只在值16之后.是否有一种更优雅的方法从项目中提取此值,而不是使用Split?

亲切的问候,

[更正了一些代码格式]


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]

推荐答案



我喜欢使用regex:

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 />}



您可以使用索引0和2,而不必再次使用.Trim(). ;-)


玩得开心



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


Have fun


您也许可以做类似的事情(我通常会使用类似的东西来读取文件,但是它似乎也可以在这里工作):

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.


这种较短的衬板怎么样?
How about this shorter one liner?
string Result = inputString.Split('[')[1].Split(']')[0];


这篇关于然后是.Split(']');的更优雅的方式.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆