public static (string result, int left, int right) MyTrim(string value, params string[] trim) {
if (string.IsNullOrEmpty(value) || trim is null || trim.Length == 0)
var span = value.AsSpan();
for (bool keep = true; keep; ) {
foreach (var item in trim)
if (!string.IsNullOrEmpty(item) && span.StartsWith(item)) {
trimmedLeft += item.Length;
span = span.Slice(item.Length);
for (bool keep = true; keep; ) {
foreach (var item in trim)
if (!string.IsNullOrEmpty(item) && span.EndsWith(item)) {
trimmedRight += item.Length;
span = span.Slice(0, span.Length - item.Length);
return (span.ToString(), trimmedLeft, trimmedRight);
public class MyTrimResult {
public MyTrimResult(string result, int left, int right) {
public string Result { get; private set; }
public int Left { get; private set; }
public int Right { get; private set; }
public static MyTrimResult MyTrimOld(string value, params string[] trim) {
if (string.IsNullOrEmpty(value) || trim is null || trim.Length == 0)
return new MyTrimResult(value, 0, 0);
for (bool keep = true; keep; ) {
foreach (var item in trim)
if (!string.IsNullOrEmpty(item) && value.StartsWith(item)) {
trimmedLeft += item.Length;
value = value.Substring(item.Length);
for (bool keep = true; keep; ) {
foreach (var item in trim)
if (!string.IsNullOrEmpty(item) && value.EndsWith(item)) {
trimmedRight += item.Length;
value = value.Substring(0, value.Length - item.Length);
return new MyTrimResult(value, trimmedLeft, trimmedRight);
public static void Main() {
string[] tests = new string[] {
var report = string.Join(Environment.NewLine, tests
.Select(test => (test, result : MyTrim(test, " ", "#", "\t", "//", "/*", "*/")))
.Select(pair => $"{pair.test,30} ===> {pair.result.result} (left: {pair.result.left}; right: {pair.result.right}) "));
Console.WriteLine(report);
var reportOld = string.Join(Environment.NewLine, tests
.Select(test => (test, result : MyTrimOld(test, " ", "#", "\t", "//", "/*", "*/")))
.Select(pair => $"{pair.test,30} ===> {pair.result.Result} (left: {pair.result.Left}; right: {pair.result.Right}) "));
Console.WriteLine(reportOld);