Reputation: 463
Hey guys just wanted to understand something here.
I have this code:
var testString = "DA DDDLY DO:DAXS D/B#BTN A TIME/DTE:0027/01NOV";
var testTrimStart = testString.TrimStart("DA ".ToCharArray());
testTrimStart outputs:
LY DO:DAXS D/B#BTN A TIME/DTE:0027/01NOV
Could someone explain why
DA DDD
is removed.
I could understand if it was
DA DA DDDLY DO....
I understand it's an array of type CHAR that it's searching for. But should it not be searching and replacing
"DA "
throughout the string?
Here's the .NET FIDDLE Link
Upvotes: 1
Views: 188
Reputation: 391336
You said:
'D'
, a 'A'
, or a space.The behavior of TrimStart
is documented in the documentation:
Removes all leading occurrences of a set of characters specified in an array from the current String object.
(my emphasis)
Basically the TrimStart method is this in pseudocode:
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)
The actual implementation is more optimal than this but this is how you could sum it up.
If you meant this:
Remove this specific substring from the start of the string if it is present
Then there are 2 ways of doing that:
Use a regex
Regex.Replace(testString, "^DA ", string.Empty);
Look for it yourself using substring and comparison
if (testString.StartsWith("DA "))
testString = testString.Substring(3); // 3 == length of "DA "
If you this:
then you have no guarantee that the replacement will occur at the very start of the string.
Upvotes: 4