ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

LeftOf

Returns the left of a string, terminated by a certain character. If the character isn't found the whole string is returned. Ex: string s = "ab-23"; s.LeftOf(s, '-') returns "ab"

Source

/// <summary>
/// Returns the first part of the strings, up until the character c. If c is not found in the
/// string the whole string is returned.
/// </summary>
/// <param name="s">String to truncate</param>
/// <param name="c">Character to stop at.</param>
/// <returns>Truncated string</returns>
public static string LeftOf(this string s, char c)
{
    int ndx = s.IndexOf(c);
    if (ndx >= 0)
    {
	return s.Substring(0, ndx);
    }

    return s;
}

Example

/// <summary>
///A test for LeftOf
///</summary>
[TestMethod()]
public void LeftOfTest()
{
	string s = "7011(7011)";
	char c = '('; 
	string expected = "7011";
	string actual;
	actual = StringExtensions.LeftOf(s, c);
	Assert.AreEqual(expected, actual);
	actual = StringExtensions.LeftOf(actual, c);	// actual is now 7011
	Assert.AreEqual(expected, actual);
}

Author: Gaston Verelst

Submitted on: 2 okt. 2009

Language: C#

Type: System.String

Views: 6563