String.Split 不删除拆分文本,只删除第一个字母 [英] String.Split is not removing the split text, only the first letter

查看:17
本文介绍了String.Split 不删除拆分文本,只删除第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是怎么回事?

issue.CallAction 具有以下值:

"Blah blah - WebSite - 9/20/2017 - Containers remaining changed to 0."

分裂它,像这样:

issue.CallAction.Split("Containers remaining changed to ").ToList()

返回超过 1 个字符串元素(本例中的预期),但元素是:

returns more than 1 string element (as expected in this case) but the elements are:

  1. 废话 - 网站 - 9/20/2017 -
  2. 剩余的容器数更改为 0.

据我了解,Split 会替换您要拆分的整个字符串,但它只会替换第一个字母.

It was my understanding that Split replaces the entire string that you're splitting yet it's only replacing the first letter.

是什么?

这是编译器对字符串分隔符感到满意的屏幕截图.注意没有愤怒的红色波浪线:

Here's a screenshot of the compiler being happy with a string separator. Note the absence of the angry red squiggle:

:

推荐答案

它看起来像是将分隔符视为 Char.至少在 Visual Studio 2017/.NET 4.5 中,我正在使用 C#,以及 当前版本没有

It looks like it's treating the separator as a Char. At least in Visual Studio 2017/.NET 4.5,C# which is what I'm using, as well as the current version there is no

string Split(string separator)

所以你必须创建一个分隔符数组并填充第一个.

so you'd have to create an array of separators and populate the first one.

试试这个:

        string s = "Blah blah - WebSite - 9/20/2017 - Containers remaining changed to 0.";

        string[] separator = { "Containers remaining changed to " };
        string[] splitted = s.Split(separator, StringSplitOptions.None);

我已经好几年没用过VB了,所以我不得不在这里重新学习.这个示例程序的输出告诉我,当调用 Char 时,VB 悄悄地将 String 强制转换为 Char:

I haven't used VB in several years, so I had to do some re-learning here. The output of this sample program tells me that VB quietly coerces a String into a Char when a Char is called for:

Sub PrintAChar(c As Char)
    Console.WriteLine("Printing your character: '" + c + "'")
End Sub

Sub Main()
    PrintAChar("B")                ' Prints 'B'
    PrintAChar("Bob Was Here.")    ' Also prints 'B'
End Sub

有关最佳实践,请参阅下面@Heinzi 的重要评论.

See @Heinzi's important comment below for a best practice.

这篇关于String.Split 不删除拆分文本,只删除第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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