C # TrimStart with string parameter

I am looking for String extension methods for TrimStart() and TrimEnd() that take a string parameter.

I could build it myself, but itโ€™s always interesting for me to see other people doing something.

How can I do that?

+48
c #
Dec 02 '10 at 14:12
source share
9 answers

To trim all occurrences (exactly matching) strings, you can use something like the following:

Trimstart

 public static string TrimStart(this string target, string trimString) { if (string.IsNullOrEmpty(trimString)) return target; string result = target; while (result.StartsWith(trimString)) { result = result.Substring(trimString.Length); } return result; } 

Trimend

 public static string TrimEnd(this string target, string trimString) { if (string.IsNullOrEmpty(trimString)) return target; string result = target; while (result.EndsWith(trimString)) { result = result.Substring(0, result.Length - trimString.Length); } return result; } 

To trim any character in trimChars from the beginning / end of the target (for example, "foobar'@"@';".TrimEnd(";@'") will return "foobar" ), you can use the following:

Trimstart

 public static string TrimStart(this string target, string trimChars) { return target.TrimStart(trimChars.ToCharArray()); } 

Trimend

 public static string TrimEnd(this string target, string trimChars) { return target.TrimEnd(trimChars.ToCharArray()); } 
+73
Dec 02 '10 at 14:16
source share

TrimStart and TrimEnd take an array of characters. This means that you can pass the string as a char array as follows:

 var trimChars = " .+-"; var trimmed = myString.TrimStart(trimChars.ToCharArray()); 

Therefore, I do not see the need for overload, which takes a string parameter.

+16
Dec 02 '10 at 14:17
source share

I thought the question is trying to trim a specific line from the beginning of a larger line.

For example, if I had the string "hellohellogoodbyehello", if you tried to call TrimStart ("hello"), you would return "goodbyehello".

If so, you can use the following code:

 string TrimStart(string source, string toTrim) { string s = source; while (s.StartsWith(toTrim)) { s = s.Substring(toTrim.Length - 1); } return s; } 

It would not be super efficient if you needed to trim a lot of lines, but if it is just for a few cases, it is easy to do.

+11
May 19 '11 at 20:18
source share

from dotnetperls.com ,

Performance

Unfortunately, the TrimStart method is not very optimized. In certain situations, you can probably write character-based iterative code that can beat it. This is because the array must be created to use TrimStart.

However: Custom code does not have to have an array. But for fast-developed applications, the TrimStart method is useful.

+3
Mar 26 '14 at 9:55 a.m.
source share

To match the entire string and not select multiple substrings, you should use the following:

  public static string TrimStart(this string source, string value, StringComparison comparisonType) { if (source == null) { throw new ArgumentNullException(nameof(source)); } int valueLength = value.Length; int startIndex = 0; while (source.IndexOf(value, startIndex, comparisonType) == startIndex) { startIndex += valueLength; } return source.Substring(startIndex); } public static string TrimEnd(this string source, string value, StringComparison comparisonType) { if (source == null) { throw new ArgumentNullException(nameof(source)); } int sourceLength = source.Length; int valueLength = value.Length; int count = sourceLength; while (source.LastIndexOf(value, count, comparisonType) == count - valueLength) { count -= valueLength; } return source.Substring(0, count); } 
+3
May 16 '18 at 21:56
source share

There is no built-in function in C #, but you can write your own extensions that behave exactly as you expect.

Note that with IndexOf / LastIndexOf you can choose whether it is case sensitive / culture or not.

I also used the "repeat cropping" function.

There is one TrimStr(..) function that works with both TrimStr(..) and three functions that implement .TrimStart(...) , .TrimEnd(...) and .Trim(..) for compatibility with .NET cropping :

Try it in DotNetFiddle

 public static class Extension { public static string TrimStr(this string str, string trimStr, bool trimEnd = true, bool repeatTrim = true, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) { int strLen; do { if (!(str ?? "").EndsWith(trimStr)) return str; strLen = str.Length; { if (trimEnd) { var pos = str.LastIndexOf(trimStr, comparisonType); if ((!(pos >= 0)) || (!(str.Length - trimStr.Length == pos))) break; str = str.Substring(0, pos); } else { var pos = str.IndexOf(trimStr, comparisonType); if (!(pos == 0)) break; str = str.Substring(trimStr.Length, str.Length - trimStr.Length); } } } while (repeatTrim && strLen > str.Length); return str; } // the following is C#6 syntax, if you're not using C#6 yet // replace "=> ..." by { return ... } public static string TrimEnd(this string str, string trimStr, bool repeatTrim = true, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) => TrimStr(str, trimStr, true, repeatTrim, comparisonType); public static string TrimStart(this string str, string trimStr, bool repeatTrim = true, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) => TrimStr(str, trimStr, false, repeatTrim, comparisonType); public static string Trim(this string str, string trimStr, bool repeatTrim = true, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) => str.TrimStart(trimStr, repeatTrim, comparisonType) .TrimEnd(trimStr, repeatTrim, comparisonType); } 

Now you can just use it as

  Console.WriteLine("Sammy".TrimEnd("my")); Console.WriteLine("moinmoin gibts gips? gips gibts moin".TrimStart("moin", false)); Console.WriteLine("moinmoin gibts gips? gips gibts moin".Trim("moin").Trim()); 

which creates the output

Sam
moin gibts gips? gips gibts moin
gibts gips? gips gibts

0
Aug 21 '17 at 8:21 on
source share

I assume that you mean that, for example, given the string "HelloWorld" and calling the function "crop" the beginning with "Hello", you will be left with "World". I would say that this is indeed a substring operation, since you are deleting part of a string of known length, not a trimming operation that removes an unknown string length.

So we created a couple of extension methods named SubstringAfter and SubstringBefore . It would be nice to have them in the framework, but they are not so much that you need to implement them. Remember to specify the StringComparison parameter and use Ordinal as the default if you make it optional.

-one
Dec 02 '10 at 14:21
source share

If you need one that hasn't used the built-in trim features for any reason, assuming you want to use an input line to trim, such as "~!" essentially the same as the built-in TrimStart with ['', '~', '!']

 public static String TrimStart(this string inp, string chars) { while(chars.Contains(inp[0])) { inp = inp.Substring(1); } return inp; } public static String TrimEnd(this string inp, string chars) { while (chars.Contains(inp[inp.Length-1])) { inp = inp.Substring(0, inp.Length-1); } return inp; } 
-one
Dec 02 '10 at 14:23
source share

A function to trim the beginning / end of a string using a string parameter, but only once (without loops, this one case is more popular, a loop can be added with an additional parameter to start it):

 public static class BasicStringExtensions { public static string TrimStartString(this string str, string trimValue) { if (str.StartsWith(trimValue)) return str.TrimStart(trimValue.ToCharArray()); //otherwise don't modify return str; } public static string TrimEndString(this string str, string trimValue) { if (str.EndsWith(trimValue)) return str.TrimEnd(trimValue.ToCharArray()); //otherwise don't modify return str; } } 

As mentioned earlier, if you want to implement the โ€œwhile loopingโ€ approach, be sure to check for an empty row, otherwise it might loop forever.

-one
Jul 11 '18 at 0:01
source share



All Articles