Signum Framework Logo
"Open framework that encourages convention over configuration, using C# code,
not XML files, to model at the right level of abstraction and achieve deadlines.
...but also has a full Linq provider, and syncs the schema for you!"
Login
RSS

Search

»



Main
Index
Map
Videos
Download
Source code
Tutorials
Forum
FAQ



Image



PoweredBy

StringExtensions static class

RSS
Modified on 2010/01/04 00:59 by JMPerez Paths: Documentation Categorized as SignumUtilities

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(); //false
"".HasText(); //false
"hello".HasText(); //true

DefaultText

Coalesce operator for strings, considering "" a null string.

public static string DefaultText(this string str, string defaultText)

Example:

((string)null).DefaultText("Hi"); //"Hi"
"".DefaultText("Hi"); //"Hi"
"hello".DefaultText("Hi"); //"Hello"

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!!"); //throws new ArgumentException("Arrgg!!");
"".AssertHasText("Arrgg!!"); //throws new ArgumentException("Arrgg!!");
"hello".AssertHasText("Arrgg!!"); //"Hello"

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", ";"); //"hi"
"".Add("hi", ";"); //"hi"
"hello".Add("hi", ";"); //"hello;hi"
"hello".Add("",";");//"hello"
"hello".Add(null,";");//"hello"

Performance consideration: Do not use this method in a loop. Use EnumerableExtensions.ToString instead

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"); //"hi"
"".AddLine("hi"); //"hi"
"hello".AddLine("hi"); //"hello\r\nhi"

RemoveDiacritics Image

Removes all diacritics (accents) from a string using this algorithm.

public static string RemoveDiacritics(this string s)


Example:

"âãäåçèéêë ìíîïðñòó ôõöùúûüý".RemoveDiacritics(); // returns "aaaaceeee iiiiðnoo ooouuuuy"

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(); 

//Result: 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:

//Gets numChars from the left. If not long enough throws InvalidOperationException.
public static string Left(this string str, int numChars)
//Gets numChars from the left. If not long enough, and throws is true, throws InvalidOperationException.
public static string Left(this string str, int numChars, bool throws)

//Gets numChars from the right. If not long enough throws InvalidOperationException. public static string Right(this string str, int numChars) //Gets numChars from the right. If not long enough, and throws is true, throws InvalidOperationException. public static string Right(this string str, int numChars, bool throws)


Example:

"Pulp Fiction".Left(4); // "Pulp"
"Amelie".Left(7); //throws InvalidOperationExcetion
"Amelie".Left(7,false); //"Amelie"

"Pulp Fiction".Right(4); // "tion" "Amelie".Right(7); //throws InvalidOperationExcetion "Amelie".Right(7,false); //"Amelie"


RemoveLeft and RemoveRight

Methods that remove a substring from the Left side or from the Right side:

//Removes numChars from the left. If not long enough throws InvalidOperationException.
public static string RemoveLeft(this string str, int numChars)
//Removes numChars from the ñeft. If not long enough, and throws is true, throws InvalidOperationException.
public static string RemoveLeft(this string str, int numChars, bool throws)

//Removes numChars from the right. If not long enough throws InvalidOperationException. public static string RemoveRight(this string str, int numChars) //Removes numChars from the right. If not long enough, and throws is true, throws InvalidOperationException. public static string RemoveRight(this string str, int numChars, bool throws)


Example:

"Pulp Fiction".RemoveLeft(4); // " Fiction"
"Amelie".RemoveLeft(7); //throws InvalidOperationExcetion
"Amelie".RemoveLeft(7,false); //""

"Pulp Fiction".RemoveRight(4); // "Pulp Fic" "Amelie".RemoveRight(7); //throws InvalidOperationExcetion "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) + "|"); //Writing: //|3 Elf | //|7 Dwarf | //|9 Mortal M| //|1 Dark Lor|

lines.ToConsole(s => "|" + s.PadChopLeft(10) + "|"); //Writing: //| 3 Elf| //| 7 Dwarf| //|Mortal Men| //| Dark Lord|

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) 

//Writes: //"En un luga(...)" // 012345678901234 //Notice how the string is exactly 15 chars long (0 to 14) with the etcString included

"En un lugar de la Mancha, de cuyo nombre no quiero acordarme".Etc(15, "...")

//Writes: //"En un lugar ..." // 012345678901234 //Notice how the string is exactly 15 chars long (0 to 14) with the etcString included

EtcLines Image

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) 

//Writes: //"En un lugar de la Mancha,(...)"

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'); 

//Returns: //Wll, ts n fr th mny, //Tw fr th shw, //Thr t gt rdy, //Nw g, ct, g

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 + "!"; 
//Result in:  "HelloJoe!"  
//You miss the space!!

string.Format("Hello {0}!", friendName);
//Result in: "Hello Joe!"  

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"); //Returns: "Hasta la vista 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" } 
});

//Returns: //A B C _abc_

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); 

//Result: // Hello // Dolly

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));
//Result: 
//SELECT
//  FirstName,
//  SecondName,
//  Address
//FROM Customers

SpacePascal Image

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(); // running on a en-US thread, returns "First Name"
"FirstName".SpacePascal(false); // retursn "First name"
"PrimerApellido".SpacePascal(); // running on a es-ES thread, returns "Primer apellido"

NiceName Image

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(); // returns "First Name"
"First_Name".NiceName(); // returns "First Name"

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(); //20.00 Bytes
1005L.ToComputerSize(); //1,005.00 Bytes
1024L.ToComputerSize(); //1.00 KBytes
3024050L.ToComputerSize(); //2.88 MBytes
4013441382L.ToComputerSize(true); //3.74 GB
12345678987654321.ToComputerSize(); //10.97 PBytes

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.



Creative Commons License Signum Framework Site by Signum Software is licensed under a Creative Commons Attribution 3.0 License.
Powered by ScrewTurn Wiki version 3.0.5.600.