Signum.Utilities.StringExtensions
Useful extension methods to deal with strings.
HasText
Equivalent to !string.IsNullOrEmpty.
public static bool HasText(this string str)
Example:
((string)null).HasText();
"".HasText();
"hello".HasText();
DefaultText
Coalesce operator for strings, considering "" a null string.
public static string DefaultText(this string str, string defaultText)
Example:
((string)null).DefaultText("Hi");
"".DefaultText("Hi");
"hello".DefaultText("Hi");
AssertHasText
Throws an exception with a custom message and if the string is null or empty, returns the string to allow chaining.
public static string AssertHasText(this string str, string errorMessage)
Example:
((string)null).AssertHasText("Arrgg!!");
"".AssertHasText("Arrgg!!");
"hello".AssertHasText("Arrgg!!");
Add
Allows concatenating two parts to an string adding a separator only both parts are not empty;
public static string Add(this string str, string part, string separator)
{
if (str.HasText())
{
if (part.HasText())
return str + separator + part;
else
return str;
}
else
return part;
}
Example:
((string)null).Add("hi", ";");
"".Add("hi", ";");
"hello".Add("hi", ";");
"hello".Add("",";");
"hello".Add(null,";");
AddLine
Same as Add, but using "\r\n" as the separator.
public static string AddLine(this string str, string part)
Example:
((string)null).AddLine("hi");
"".AddLine("hi");
"hello".AddLine("hi");
RemoveDiacritics 
Removes all diacritics (accents) from a string using
this algorithm.
public static string RemoveDiacritics(this string s)
Example:
"âãäåçèéêë ìíîïðñòó ôõöùúûüý".RemoveDiacritics();
Lines
Splits a string by "\r\n", or returns an empty array if the string is empty.
@"I've seen things you people wouldn't believe.
Attack ships on fire off the shoulder of Orion.
I watched C-beams glitter in the dark near the Tannhauser gate.
All those moments will be lost in time, like tears in rain.
Time to die.".Lines();
new string[]
{
"I've seen things you people wouldn't believe.",
"Attack ships on fire off the shoulder of Orion.",
"I watched C-beams glitter in the dark near the Tannhauser gate.",
"All those moments will be lost in time, like tears in rain.",
"Time to die."
};
Left and Right ¶
Methods that take the substring from the Left side or from the Right side:
public static string Left(this string str, int numChars)
public static string Left(this string str, int numChars, bool throws)
public static string Right(this string str, int numChars)
public static string Right(this string str, int numChars, bool throws)
Example:
"Pulp Fiction".Left(4);
"Amelie".Left(7);
"Amelie".Left(7,false);
"Pulp Fiction".Right(4);
"Amelie".Right(7);
"Amelie".Right(7,false);
RemoveLeft and RemoveRight ¶
Methods that remove a substring from the Left side or from the Right side:
public static string RemoveLeft(this string str, int numChars)
public static string RemoveLeft(this string str, int numChars, bool throws)
public static string RemoveRight(this string str, int numChars)
public static string RemoveRight(this string str, int numChars, bool throws)
Example:
"Pulp Fiction".RemoveLeft(4);
"Amelie".RemoveLeft(7);
"Amelie".RemoveLeft(7,false);
"Pulp Fiction".RemoveRight(4);
"Amelie".RemoveRight(7);
"Amelie".RemoveRight(7,false);
PadChopLeft and PadChopRight ¶
Adjusts the size of the string to the provided length at any rate, doing a substring or a pad depending what's necessary.
public static string PadChopRight(this string str, int length)
public static string PadChopLeft(this string str, int length)
Example:
string[] lines = new []
{
"3 Elf",
"7 Dwarf",
"9 Mortal Men",
"1 Dark Lord"
};
lines.ToConsole(s => "|" + s.PadChopRight(10) + "|");
lines.ToConsole(s => "|" + s.PadChopLeft(10) + "|");
Etc
Cuts a string to be smaller than a given length, if so, adds some indicator at the end. "(...)" it's the default.
public static string Etc(this string str, int max)
public static string Etc(this string str, int max, string etcString)
Example:
"En un lugar de la Mancha, de cuyo nombre no quiero acordarme".Etc(15)
"En un lugar de la Mancha, de cuyo nombre no quiero acordarme".Etc(15, "...")
EtcLines 
Like Etc, but it stops whenever it finds a carriage return.
public static string EtcLines(this string str, int max)
public static string EtcLines(this string str, int max, string etcString)
Example:
@"En un lugar de la Mancha,
de cuyo nombre no quiero acordarme".EtcLines(100)
RemoveChars
Removes a set of chars from a string:
public static string RemoveChars(this string str, params char[] chars)
Example:
@"Well, its one for the money,
Two for the show,
Three to get ready,
Now go, cat, go".RemoveChars('a', 'e', 'i', 'o', 'u');
Formato (Very Useful!!)
Formato is just another extension method for calling string.Format in a sorter way.
string.Format is ok, it's better than error prone string concatenation:
"Hello" + friendName + "!";
string.Format("Hello {0}!", friendName);
However, usually you realize that you will need string format when you are already writing the string, having to jump back to the start of the string. Making string.Format an instance method will have solved the problem, but this is something for Microsoft to do. Our only option is to make an extension method.
Why this name? Well, Format is already in use, FormatWith is too long, F is too short, so we keep it the way it was before translating everything to English: Formato
public static string Formato(string format, object arg0)
public static string Formato(string format, object arg0, object arg1)
public static string Formato(string format, object arg0, object arg1, object arg2)
public static string Formato(this string pattern, params object[] parameters)
public static string Formato(this string format, IFormatProvider provider, params object[] args)
Example:
"Hasta la vista {0}".Formato("baby");
Replace
Applies a dictionary from original->replacement strings to a given value.
If more than one replacement could be applied, the one added before to the dictionary wins.
public static string Replace(this string str, Dictionary<string, string> replacements)
Example:
var a = @"a b c abc".Replace(new Dictionary<string, string>()
{
{ "abc", "_abc_" },
{ "a", "A" },
{ "b", "B" },
{ "c", "C" }
});
Indent
Adds a number of starting chars (spaces by default) at the beginning of any line in a given string.
public static string Indent(this string str, int numChars)
public static string Indent(this string str, int numChars, char indentChar)
Example:
@"Hello
Dolly".Indent(3);
It's useful for code generation, like C# or SQL statements:
"SELECT\r\n{0}\r\nFROM Customers".Formato(
new[] { "FirstName", "SecondName", "Address" }.ToString(",\r\n").Indent(2));
SpacePascal 
Returns a "StringLikeThis" into a normal "String Like This". By default preserves uppercase in English but it doesn't in other languages like Spanish.
public static string SpacePascal(this string pascalStr)
public static string SpacePascal(this string pascalStr, bool preserveUppercase)
Example:
"FirstName".SpacePascal();
"FirstName".SpacePascal(false);
"PrimerApellido".SpacePascal();
NiceName 
If the string has '_', splits by '_', otherwise uses SpacePascal. Used for default description for field, types and properties.
public static string NiceName(this string memberName)
"FirstName".NiceName();
"First_Name".NiceName();
ToComputerSize
This simple method that is an extension for
long (not string). Given a long number with the length in bytes for some amount of data, returns a human readable string using Bytes,KiloBytes,MegaBytes...
public static string ToComputerSize(this long value)
public static string ToComputerSize(this long value, bool useAbbreviations)
Example:
20L.ToComputerSize();
1005L.ToComputerSize();
1024L.ToComputerSize();
3024050L.ToComputerSize();
4013441382L.ToComputerSize(true);
12345678987654321.ToComputerSize();
As
wikipedia notes, according to the International Electrotechnical Commission in 2000, multiples of 1024 should be noted using Kibi(Ki) instead of Kilo(K) to avoid confusion with multiples of 1000. It looks that this standard is being ignored and everybody stills using KiloByte(KB) to note 1024 Bytes, so we divide by 1024 in this extension method.