Reputation: 2629
How do we check if the string contains any numbers?
The best way to check if the string contains all letters is to use isletter
command but how to go one step further and check if any char in the string is a number?
One way is to convert the string to an array of Chars and cross check if the ascii values belongs to numerics. Is there a simpler way to do this in MATLAB?
Example string: 67 Cliston St
Upvotes: 2
Views: 7186
Reputation: 2854
This is by no means the best way (I'm sure someone else will have a more elegant solution). But this appears to work.
Approach:
1. Split the string up using split
.
2. Trim whitespace from the string with strtrim
.
3. Use str2num
, isempty
, & isnumeric
to check for numbers.
str = '67 Cliston St'
newStr = strtrim(split(str))
idxNum = false(length(newStr),1);
for k =1:length(newStr)
if ~isempty(str2num(newStr{k}))
idxNum(k) = isnumeric(str2num(newStr{k}))
end
end
NumPresent = any(idxNum,true); % returns true if any numerics in the str
As I said, it's not pretty. The other answers are superior. This would fail for '67Cliston St'
unless you break down the string to each character like
newStr = strtrim(split(str,""))
which would work fine for '67Cliston St'
.
Computational Performance:
Comparing this answer against the other answers:
showed that isstrprop(str,'digit')
is much faster as the length of the string increases.
Upvotes: 1
Reputation: 26014
>> exampleString = "67 Cliston St";
>> any(regexp(exampleString ,'[0-9]'))
will return true if there is at least one number in the string.
Upvotes: 3