MATLAB Answers

0

How to check the numbers of characters of a string?

Asked by Ze Kai Ng on 31 Oct 2012
e.g I have a string, abcde. And I need a checker to check whether the string has 5 characters before executing a command.

  0 Comments

Sign in to comment.

Products

5 Answers

Answer by Pedro Villena on 31 Oct 2012
Edited by Pedro Villena on 31 Oct 2012
 Accepted Answer

str = num2str([17;10],'%05i')
if length(str(1,:))==5,
%%%here is your command
end
or
str = num2str([17;10],'%05i')
if numel(str(1,:))==5,
%%%here is your command
end

  3 Comments

This won't work, consider:
num2str([17;10],'%05i')
ans =
00017
00010
length(ans)
Better to use NUMEL, for generality.
S = ['ertyu';'poiuy';'lkjhg';'nbvcx']
length(S)
numel(S)
I should have hit refresh, I guess ;-).

Sign in to comment.


Answer by Sean de Wolski
on 31 Oct 2012

Pedro's code with numel as the size check:
numel(str)==5

  0 Comments

Sign in to comment.


Answer by manoj saini on 31 Oct 2012

>>a='string'; >>n=length(a) so n will return length of a string

  0 Comments

Sign in to comment.


Answer by Ze Kai Ng on 31 Oct 2012

I converted my string into vector form and cannot count using length(str).

  0 Comments

Sign in to comment.


Answer by Ze Kai Ng on 31 Oct 2012

Thank you everybody! I figured it out. I need to char(vec(pos)) first to convert to string then I can compare with the above methods.

  0 Comments

Sign in to comment.