.RemoveExtraWhitespace();
Removed extra whitespace from a string for NET8 and higher.
Source
using System.Diagnostics;
namespace TODO;
public static class StringExtensions
{
/// <summary>
/// Remove extra whitespace and trim whitespace from start and end of the string
/// </summary>
/// <param name="input">string to work on</param>
/// <returns>The string with extra whitespace removed and whitespace trimmed from start and end</returns>
[DebuggerStepThrough]
public static string RemoveExtraWhitespace(this string input)
{
if (string.IsNullOrEmpty(input))
return input;
Span<char> result = stackalloc char[input.Length];
var resultIndex = 0;
var isWhitespace = false;
foreach (var currentChar in input)
{
if (char.IsWhiteSpace(currentChar))
{
if (isWhitespace) continue;
result[resultIndex++] = ' ';
isWhitespace = true;
}
else
{
result[resultIndex++] = currentChar;
isWhitespace = false;
}
}
return result[..resultIndex].ToString().Trim();
}
}
Example
var withSpaces = " This is a long string ";
string removeSpaces = withSpaces.RemoveExtraWhitespace();