How can I find the number of letters in a string? Just letters (A-Z, a-z)?

 Respuesta aceptada

Easiest way:
string = 'This is a string.';
NrLtrs = length(regexpi(string, '[a-zA-Z]'));
The number of letters only is returned in the ‘NrLtrs’ variable.

7 comentarios

I have a question about text files. how to calculate the total number of letters (A-Z, a-z) in the whole text file?
I would believe the same way. The text file would have to be in the same variable, so you would have to read the entire file in first.
I did like this but it gives error:
fid = fopen(filename, 'rt');
if fid < 0
-1;
return;
end
s = textscan(fid,'%s','Delimiter','\n');
num = length(regexpi(s, '[a-zA-Z]'));
fclose(fid);
disp(num);
What error does it give?
What line?
Error using regexpi
All cells must be strings.
Error in letter_counter (line 8)
num = length(regexpi(s, '[a-zA-Z]'));
Why are you using textscan to simply get a string. That's too overkill for a simple case like this. Simply use fgetl() if you want to get line by line, or use fread() if you want to suck up the whole file in one shot.
If it’s a cell, address it as a cell:
string = {'This is a string.'};
NrLtrs = length(regexpi(string{1}, '[a-zA-Z]'));
You will likely have to experiment with this idea in the context of your code to get the result you want.

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 23 de Mayo de 2015

Comentada:

el 24 de Mayo de 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by