วันศุกร์ที่ 25 มกราคม พ.ศ. 2551

Extension Methods for String

This post continues on extension methods, now for string. String is the most common type in all programming languages. It is a human-readable text for any kind of information. These are some more extension methods, which may make you to present your data easier.

public static string Join(this IEnumerable<string> source, string separator) {
    string[] value = source as string[];
    if (value != null)
        return string.Join(separator, value);

    return string.Join(separator, source.ToArray());
}
public static string Reverse(this string text) {
    int len = text.Length;
    char[] charArray = new char[len--];
    for (int i = 0; len >= 0; i++, len--)
        charArray[i] = text[len];
    return new string(charArray);
}
public static string Repeat(this string source, int num) {
    if (num <= 0)
        return string.Empty;

    StringBuilder sb = new StringBuilder(source.Length * num);

    num.Times(x => sb.Append(source));
    return sb.ToString();
}


Join method is the same as String.Join, but this is for enumerable of string. Below is example.

var result = new[] { "Hello", "World!" }.Join(", ");
//result = "Hello, World!"


Reverse method is to reverse the character order of a string. Below is example.

var result = "Hello, World!".Reverse();
// result = "!dlroW ,olleH"


Repeat method is to duplicate a string for specific number of times. Below is example.

var result = "Hello, World!".Repeat(3);
// result = "Hello, World!Hello, World!Hello, World!"


Some more useful methods used to transform enumerable of objects to a string, which I always use when debugging. Following is the code.

public static string ListMembers<T>(this IEnumerable<T> source, string format, string separator) {
    return source.Select(s => string.Format(format, s)).Join(separator);
}
public static string ListMembers<T>(this IEnumerable<T> source) {
    return source.Select(s => s.ToString()).Join(" ");
}


ListMembers method can be used as ToString method. It transforms every object to string and join them together. Below is example.

var result = new[] { 1, 2, 3, 4, 5 }.ListMembers();
//result = "1 2 3 4 5"

Next post, go to interesting topic about finding solutions by specifying constraints. It is called Constraint Programming.

ไม่มีความคิดเห็น: