Skip to content

Instantly share code, notes, and snippets.

@kururu-abdo
Forked from karenpayneoregon/Extensions.cs
Created March 21, 2024 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kururu-abdo/fb4c8ce5aaed87fe5e4a874d6a8356ad to your computer and use it in GitHub Desktop.
Save kururu-abdo/fb4c8ce5aaed87fe5e4a874d6a8356ad 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment