嘿伙计们只是想在这里了解一些东西。
我有这个代码:
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/