如何正确使用Split属性 [英] how to properly use the Split property
问题描述
我正在尝试在消息框中显示用户选择的项目。
以下命令可以找到。
MessageBox.Show(listBox1.SelectedItem.ToString());
我想通过使用如下所示的分割命令在空格后抑制部分选定项目:
Am am trying to display the user selected item in a messagebox.
The following command works find.
MessageBox.Show(listBox1.SelectedItem.ToString());
I would like to suppress part of the Selected Item after a blank space by using the Split Command like this:
string test=listBox1.SelectedItem.ToString().Split(' ');
MessageBox.Show(test[0]);
在尝试编译时,我收到以下错误消息:
错误1无法将类型''string []''隐式转换为''string''C: \ WindowsWindowsFormsApplication6 \ WindowsFormsApplication6 \Form1.cs 41 25 WindowsFormsApplication6
我应该使用另一个属性或方法来执行此操作吗?
When attempting to compile this I get the following error message:
Error 1 Cannot implicitly convert type ''string[]'' to ''string'' C:\WindowsFormsApplication6\WindowsFormsApplication6\Form1.cs 41 25 WindowsFormsApplication6
Is there another property or method I should be using to do this?
推荐答案
Split返回一个您尝试设置为字符串测试的数组。你几乎拥有它。结合你的两行代码并执行以下操作:
Split returns an array which you are trying to set into string test. You almost have it. Combine your two lines of code and do this:
string test=listBox1.SelectedItem.ToString().Split(' ')[0];
这将返回数组中的第一项一个字符串。
This will return the first item in the array as a string.
string[] test = myListBox.SelectedItem.ToString().Split(new char[] {' '});
if (test.Length > 0)
MessageBox.Show(test[0]);
或,在某些情况下,
or, in some cases,
string[] test = myListBox.SelectedItem.ToString().Split(new char[] {' '}, System.StringSplitOptions.RemoveEmptyEntries);
if (test.Length > 0)
MessageBox.Show(test[0]);
顺便说一句,请注意违反 listBox1
中的命名约定。设计人员自动生成代码根本不能(也不应该)做得更好,但是将所有自动生成的名称重命名为语义合理的东西是你的事;从不使用自动生成的名称。
By the way, pay attention for violation of the naming conventions in listBox1
. Auto code generation by designer simply cannot (and should not) do better, but it''s your business to rename all auto-generated names to something semantically sensible; never use auto-generated names as is.
>
分割函数总是返回字符串数组。所以使用:
Hi,
Split function always return array of string. So use:
string[] test=listBox1.SelectedItem.ToString().Split(' ');
我希望这会有所帮助。
谢谢:)
I hope this will help.
Thanks :)
这篇关于如何正确使用Split属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!