Extend some useful string functions in C#

Add some useful extension methods for string manipulations in C#. Make coding more elegent, interesting and productive.

string.ToBoolean();
string.ToInt();
string.RemoveSufix(string suffix);
string.RemovePrefix(string prefix);
string.Remove(string toBeRemoved);
string.RemoveSpace();
string.RemoveWhiteSpace();

 

/// <summary>
/// Accept string value: "true", "t", "1" as true, all others will be evaluated as false.
/// </summary>
/// <returns></returns>
public static bool ToBoolean(this string value)
{
	if (string.IsNullOrEmpty(value)) return false;

	switch (value.Trim().ToLower())
	{
		case "true":
			return true;
		case "t":
			return true;
		case "1":
			return true;
		case "0":
			return false;
		case "false":
			return false;
		case "f":
			return false;
		case "":
			return false;
		default:
			return false;
			//throw new InvalidCastException("You can't cast that value to a bool!");
	}
}
/// <summary>
/// Convert a string to int with default value
/// </summary>
/// <returns></returns>
public static int ToInt(this string value)
{
	if (string.IsNullOrEmpty(value)) return 0;

	int.TryParse(value, out int i);
	return i;
}

/// <summary>
/// Remove string suffix
/// </summary>
/// <param name="suffix"></param>
/// <returns></returns>
public static string RemoveSufix(this string value, string suffix)
{
    if (value.EndsWith(suffix))
    {
		value.Substring(0, value.Length - suffix.Length);
    }
	return value;
}

/// <summary>
/// Remove string prefix
/// </summary>
/// <param name="prefix"></param>
/// <returns></returns>
public static string RemovePrefix(this string value, string prefix)
{
	if (value.StartsWith(prefix))
	{
		value.Substring(prefix.Length);
	}
	return value;
}

/// <summary>
/// Remove all spaces from a string
/// </summary>
/// <returns></returns>
public static string RemoveSpace(this string value)
{
	return value.Replace(" ", string.Empty);
}

/// <summary>
/// Remove all white spaces from a string, including " ", \t, \r, \n
/// </summary>
/// <returns></returns>
public static string RemoveWhiteSpace(this string value)
{
	return value.Replace(" ", string.Empty)
		.Replace("\t", string.Empty)
		.Replace("\r", string.Empty)
		.Replace("\n", string.Empty);
}
/// <summary>
/// Remove specified substring from the string
/// </summary>
/// <param name="value"></param>
/// <param name="toBeRemoved"></param>
/// <returns></returns>
public static string Remove(this string value, string toBeRemoved)
{
	return value.Replace(toBeRemoved, string.Empty);
}

 764 total views

Author: Albert

Leave a Reply