ExtensionMethod.NET Home of 855 C#, Visual Basic, F# and Javascript extension methods

EnsureEndsWith

Ensures that a string ends with a given suffix.

Source

/// <summary>
/// 	Ensures that a string ends with a given suffix.
/// </summary>
/// <param name = "value">The string value to check.</param>
/// <param name = "suffix">The suffix value to check for.</param>
/// <returns>The string value including the suffix</returns>
/// <example>
/// 	<code>
/// 		var url = "http://www.pgk.de";
/// 		url = url.EnsureEndsWith("/"));
/// 	</code>
/// </example>
public static string EnsureEndsWith(this string value, string suffix)
{
    return value.EndsWith(suffix) ? value : value.Insert(value.Length, suffix);
}

Example

var sentence = "This is a sentence".EnsureEndsWith(".");

Author: John Tolar

Submitted on: 25 mrt 2022

Language: csharp

Type: System.String

Views: 290