如何仅删除一个字符C# [英] How to remove only one character c#

查看:62
本文介绍了如何仅删除一个字符C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ex

列表框

我的名字
她的名字
你的名字.

我只想删除."

我的名字
她的名字
你的名字

从非解决方案中移出

ex

Listbox

my name
her name
your name.

I want to remove only "."

my name
her name
your name

Moved from non-solution

string[] dataFromFile = lstQiftet.Items.Cast<string>().ToArray();

           ArrayList arr = new ArrayList();

           foreach (string s in dataFromFile)




我尝试了s.remove(.";).... s.TrimEnd(.")......不起作用
[/Edit]




I tried s.remove(".";).... s.TrimEnd(".")...... dont work
[/Edit]

推荐答案

假设要修改原始数组,正确执行此操作的方法是:

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方法是一个不错的选择.

以下代码可用于测试以上几点.
The TrimEnd method and other methods to remove the . work. But the issue may be reassigning the modified list of items to the ListBox.

The Items property of ListBox is a ReadOnly property, hence it can be used to retrieve the existing list of items, but it cannot be assigned back. Hence, the DataSource property can be used to set the modified list.

The TrimEnd(''.'') works but if there are spaces at the end then it will not work. So, it is better to use TrimEnd(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 use TrimEnd 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(".", "");


这篇关于如何仅删除一个字符C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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