Florin M.
Florin M.

Reputation: 2169

Split string before any first number

string test = " Puerto Rico 123 " ;

I would like to obtain only "Puerto Rico". The idea is that instead of 123 it can be any number. How can I achieve this?

Upvotes: 5

Views: 13325

Answers (5)

Caspar Kleijne
Caspar Kleijne

Reputation: 21864

Simple Trim would do, IF the number would only appear on the END of the string:

var result = "Puerto Rico 123".TrimEnd(" 1234567890".ToCharArray());

or

  string source ="Puerto Rico 123";
  char[] toBeRemoved = " 1234567890".ToCharArray(); <-- note the whitespace...
  string result = source.TrimEnd(toBeRemoved); <-- remove the chars at the end     of the source

Upvotes: 2

Afnan Ahmad
Afnan Ahmad

Reputation: 2542

You can use the Regex like this:

Regex MyRegex = new Regex("[^a-z A-Z.]", RegexOptions.IgnoreCase);
string s = MyRegex.Replace(@" Puerto Rico 123 ", @"");
Console.WriteLine(s);

Upvotes: 0

msmolcic
msmolcic

Reputation: 6577

You could do it with Regex as suggested, but you can try with this one as well:

var str = " Puerto Rico 123 ";
var firstDigit = str.FirstOrDefault(c => char.IsDigit(c));

if (firstDigit != default(char))
{
    var substring = str.Substring(0, str.IndexOf(firstDigit));
}

It returns the value of the first digit in your string if there is any, or '\0' if there is no digit in your string. After that, we check if first digit is anything other than '\0', if so, we take substring of the initial string from the beginning until the first occurrence of the digit in your string.

Upvotes: 4

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

I suggest using regular expressions which is quite easy in the context: get all the non-digit [^0-9]* characters from the beginning ^ of the string:

string test = " Puerto Rico 123 ";

string result = Regex.Match(test, @"^[^0-9]*").Value;

Linq is an alrernative:

string result = string.Concat(test.TakeWhile(c => c < '0' || c > '9'));

In case you want to trim the leading and trailing spaces (and have "Puerto Rico" as the answer, not " Puerto Rico "), just add .Trim(), e.g.:

string result = Regex.Match(test, @"^[^0-9]*").Value.Trim();

Upvotes: 8

nicolas
nicolas

Reputation: 7668

You can do that with a Regex like this:

Match match = Regex.Match("Puerto Rico 123", @"^.*?(?=\d)");
string text = match.Value;

Upvotes: -1

Related Questions