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?
To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.
Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
a = a. replaceAll("[0-9]+","$1 "); String[] b = a. split(" "); It can also be customized in case your string contains other spaces, by substituting a character guaranteed not to appear in your string instead of the space.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With