LeftOf

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

Description

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"

Details

Double click on the code to select all.

 

;