更新时间:2023-11-17 18:17:34
假设要修改原始数组,正确执行此操作的方法是:
The way to do it correctly assuming that you want to modify the original array would be:
for (int i = 0, count = dataFromFile.Length; i != count; ++i)
{
dataFromFile[i] = dataFromFile[i].TrimEnd('.');
}
TrimEnd
方法和其他删除.
工作的方法.但是问题可能是将修改后的项目列表重新分配给ListBox
.ListBox
的Items
属性是ReadOnly
属性,因此可以用于检索现有的项目列表,但不能将其分配回来.因此,DataSource
属性可用于设置修改后的列表.TrimEnd(''.'')
有效,但是如果末尾有空格,则它将无效.因此,***使用TrimEnd(new char[]{''.'','' ''})
来确保即使有尾随空格也要删除.
.既然如此,只需要删除即可.在字符串的末尾,我认为使用TrimEnd
方法是一个不错的选择.
以下代码可用于测试以上几点.
TheTrimEnd
method and other methods to remove the.
work. But the issue may be reassigning the modified list of items to theListBox
.
TheItems
property ofListBox
is aReadOnly
property, hence it can be used to retrieve the existing list of items, but it cannot be assigned back. Hence, theDataSource
property can be used to set the modified list.
TheTrimEnd(''.'')
works but if there are spaces at the end then it will not work. So, it is better to useTrimEnd(new char[]{''.'','' ''})
to ensure that the.
is removed even if there are trailing spaces. Since, it is required to remove only the . at the end of the string, I think it is a good option to useTrimEnd
method.
The following code can be used to test the above points.
void Main()
{
Form form1 = new Form();
ListBox listBox1 = new ListBox();
listBox1.Items.AddRange(new string[]{"my name","her name","your name. "});
form1.Controls.Add(listBox1);
form1.ShowDialog();
//Convert to ToList to set DataSource property of ListBox
//Trim() is required to remove the extra space for the TrimEnd to work on .
var items = listBox1.Items.Cast<string>().Select (s => s.TrimEnd(new char[]{'.',' '})).ToList();
//This will not compile as Items property is read only.
//listBox1.Items = items;
listBox1.DataSource=items;
form1.ShowDialog();
}
s.Replace(".", "");