C# TrimStart 奇怪的行为

标签 c#

嘿伙计们只是想在这里了解一些东西。

我有这个代码:

        var testString = "DA DDDLY DO:DAXS      D/B#BTN A   TIME/DTE:0027/01NOV";
        var testTrimStart = testString.TrimStart("DA ".ToCharArray());

testTrimStart 输出:

LY DO:DAXS D/B#BTN A TIME/DTE:0027/01NOV

谁能解释一下原因

DA DDD

已删除。

如果是的话我能理解

DA DA DDDLY DO....

我知道它正在搜索的是一个 CHAR 类型的数组。但它不应该是搜索和替换

"DA "

整个字符串?

这是 .NET FIDDLE链接

最佳答案

你说:

  • 修剪掉字符串开头的每个字符,无论是 'D''A' 还是空格。

TrimStart 的行为记录在 documentation 中:

Removes all leading occurrences of a set of characters specified in an array from the current String object.

(我的重点)

TrimStart 方法基本上是这样的伪代码:

if first character of string is either a 'D', a 'A', or a space
    then remove that character
    and repeat this algorithm for the next character (which is now the first)

实际实现比这更优化,但您可以这样总结。


如果你是这个意思:

Remove this specific substring from the start of the string if it is present

那么有两种方法可以做到这一点:

  • 使用正则表达式

    Regex.Replace(testString, "^DA ", string.Empty);
    
  • 自己用子串和比较找

    if (testString.StartsWith("DA "))
        testString = testString.Substring(3); // 3 == length of "DA "
    

如果你这样:

  • 一个简单的替换

那么您无法保证替换将发生在字符串的最开头。

关于C# TrimStart 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47050023/

相关文章:

c# - 从方法返回 boolean 值

c# - VB 2008 将字符串 "08:30:00"转换为日期时间 "08:30:00"

c# - 查询中带有 URL 的 WCF 数据服务

c# - 如何验证文本框是否输入了有效的货币值?

c# - HttpContent.ReadAsByteArrayAsync() 在 DelegatingHandler 内部失败且没有错误

c# - 为什么我不能在 Visual Studio 中合并项目 sdk 版本?

c# - Unity 通过网络发送和接收麦克风音频

c# - LINQ:在 IEnumerable<T> 中分配属性值

c# - Firefox 浏览器不会重新加载更新的 CSS/JS 文件

c# - Windows Phone 7 下的脚本库