Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Last active April 4, 2024 00:44
Show Gist options
  • Save karenpayneoregon/44b1aa458bb004c682da886d1d0af728 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/44b1aa458bb004c682da886d1d0af728 to your computer and use it in GitHub Desktop.
Working with strings and ternary operator

Some useful string extensions making use of ternary operator and indexors.

Usage

string sentence = "Hello    World  nice to be   here      ";
Console.WriteLine($"'{sentence}'");
Console.WriteLine($"'{sentence.RemoveExtraSpaces()}'");
Console.WriteLine($"'{sentence.RemoveExtraSpaces().TrimLastCharacter()}'");
Console.WriteLine($"'{sentence.RemoveExtraSpaces().ReplaceLastOccurrence(" ", "!!!")}'");

using System.Text.RegularExpressions;
public static class StringExtensions
{
// remove double spaces
public static string RemoveExtraSpaces(this string sender, bool trimEnd = false)
{
const RegexOptions options = RegexOptions.None;
var regex = new Regex("[ ]{2,}", options);
var result = regex.Replace(sender, " ");
return trimEnd ? result.TrimEnd() : result;
}
// trim end
public static string TrimLastCharacter(this string sender)
=> string.IsNullOrWhiteSpace(sender) ?
sender :
sender[..^1];
// replace last occurrence with replacement.
public static string ReplaceLastOccurrence(this string sender, string find, string replace)
{
int place = sender.LastIndexOf(find, StringComparison.Ordinal);
return place == -1 ?
sender :
sender.Remove(place, find.Length)
.Insert(place, replace);
}
}
@karenpayneoregon
Copy link
Author

thanks

very useful

Your very welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment