Search code examples
c#stringlimit

How can I limit a string to just the first word or the text upbeat not including the first semicolon?


I have a string that contains words like these:

var a = "abc";
var a = "abc;";
var a = "abc; def";
var a = "abc def";
var a = "abc; def";

Does anyone have any suggestions on how I could create a new string that would in all these cases (including if the termination character was a period or anything other than a-z and A-Z), consist only of "abc"?


Solution

  • Few examples:

    // Using regex, assuming English alphabet and ASCII
    var a = Regex.Split("abc;abc", "[^a-zA-Z]").First();
    
    // Using System.Linq, preferable!
    var b = string.Concat("abc abc".TakeWhile(c => char.IsLetter(c)));