Closed
Description
The String
class is missing some helper methods for string manipulation that are commonly needed. Of course it is possible for developers to add extension methods but that should not be required. here, I'll propose a list of methods that I think can be easily understood and are commonly required. The ordering of this list starts with the least controversial in my mind.
bool Contains(this string str, string value, StringComparison comparisonType)
. We have no Contains version that takes a StringComparison. The workaround withIndexOf
is awkward and feels like magic.Replace(..., StringComparison)
. Right now,Replace
always usesOrdinal
.string Left(this string str, int count)
as well asRight
.Left
is equivalent tostr.Substring(0, count)
but right isstr.Substring(str.Length - count, count)
.Truncate(int maxLength)
. This is not equivalent to Substring(maxLength) because Substring throws if the string is short.bool IsValidIndex(this string str, int index)
tests whether the argument can be used to obtain a character from the indexer. That sometimes comes in handy. Alsobool IsValidRange(this string str, int index, int count)
. Both can be useful forDebug.Assert
assertions.string TrimPrefix(this string str, string prefix)
as well asTrimPostfix
. It turns out that when working with externally generated strings (ETL processes) it is very common to need to remove a prefix. For example to get a JIRA issue number as an int you doint.Parse("PROJ-2317".TrimPrefix("PROJ-"))
.Replace(..., "PROJ-", "")
is not equivalent and semantically wrong. TheTrimStart
method cannot be used here. Further helper methods would beEnsurePrefix/Postfix
.- Some helpers to work on strings that might be null or empty. This comes up all the time.
public static string EmptyToNull(this string str)
{
return string.IsNullOrEmpty(str) ? null : str;
}
public static string NullToEmpty(this string str)
{
return str ?? string.Empty;
}
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
public static bool IsNullOrWhitespace(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
SplitLines()
. Returns the string split into lines. Need to define how to deal with OS-specific line endings. Probably, this should just bestr.Replace("\r", "").Split('\n')
which seems to work for everything.
I can see some issues with some of these proposals. They are not perfect but I want to get the discussion going. I feel the BCL has a blind spot here. The list certainly starts out with a few no-brainers.