Skip to content

Instantly share code, notes, and snippets.

@ianoxley
Created May 14, 2009 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianoxley/111696 to your computer and use it in GitHub Desktop.
Save ianoxley/111696 to your computer and use it in GitHub Desktop.
Some string extension methods for C# 3.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace GitHub.Gist {
/// <summary>
/// Extension methods for working with strings
/// </summary>
public static class StringHelpers {
/// <summary>
/// Allow us to do <c>foo.IsNullOrEmpty()</c> rather than the slightly
/// more verbose <c>string.IsNullOrEmpty(foo)</c>
public static bool IsNullOrEmpty(this string s) {
return string.IsNullOrEmpty(s);
}
/// <summary>
/// Replaces all spaces in <c>s</c> with the hyphen "-"
/// </summary>
/// <param name="s">The s.</param>
/// <returns></returns>
public static string Hyphenate(this string s) {
return Regex.Replace(s, @"(\s+|%20|\+)", "-");
}
/// <summary>
/// Unhyphenates the specified string <c>s</c> by replacing all hyphens
/// with a single space.
/// </summary>
/// <param name="s">The s.</param>
/// <returns></returns>
public static string Unhyphenate(this string s) {
return Regex.Replace(s, @"-", " ");
}
/// <summary>
/// Capitalises the first letter of each word in <c>s</c>.
/// </summary>
/// <param name="s">The s.</param>
/// <returns></returns>
public static string Capitalise(this string s) {
return Regex.Replace(s, @"\b[a-z]", m => m.Value.ToUpper());
}
// Regex methods so we can operate directly on string objects, rather
// than using the static Regex class methods
public static bool IsMatch(this string s, string pattern) {
return Regex.IsMatch(s, pattern);
}
public static string[] Split(this string s, string pattern) {
return Regex.Split(s, pattern);
}
public static Match Match(this string s, string pattern) {
return Regex.Match(s, pattern);
}
public static MatchCollection Matches(this string s, string pattern) {
return Regex.Matches(s, pattern);
}
public static bool IsInt32(this string s) {
int tmp;
if (Int32.TryParse(s, out tmp)) {
return true;
}
return false;
}
public static bool IsNotInt32(this string s) {
return !IsInt32(s);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment