Reputation: 2169
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
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
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
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
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
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