Borrar filtros
Borrar filtros

Array of ASCII Characters to String

21 visualizaciones (últimos 30 días)
Parker
Parker el 30 de Nov. de 2023
Comentada: Steven Lord el 30 de Nov. de 2023
word = string(input("Input: ","s"));
word2 = [];
for n = char(97:122)
for x = 1:strlength(word)
if contains(word{1}(x:x),n)
word2(x) = n;
end
end
end
word = string(word2);
I want to have any input and only use the letters in it. I went through this process but it returns a character array of ASCII values, either how do I remove all no letters from a string input or how do I convert an ASCII array back to a string.

Respuesta aceptada

Stephen23
Stephen23 el 30 de Nov. de 2023
Editada: Stephen23 el 30 de Nov. de 2023
Forget about loops and doing everything one-at-a-time as if MATLAB was some poor low-level language.
Think in terms of arrays and indexing. Here is one approach:
S = "UPPERCASElowercase!£%&*"
S = "UPPERCASElowercase!£%&*"
X = S{1}<97 | S{1}>122;
S{1}(X) = []
S = "lowercase"
You could also use ISSTRPROP, or REGEXPREP, or various other approaches that do not require any loops.
  1 comentario
Steven Lord
Steven Lord el 30 de Nov. de 2023
I'm partial to isstrprop, as you mentioned in your last sentence, as it doesn't depend on "magic numbers".
S = "UPPERCASElowercase!£%&*"
S = "UPPERCASElowercase!£%&*"
lowercaseLetterLocations = isstrprop(S, "lower");
S{1}(lowercaseLetterLocations)
ans = 'lowercase'

Iniciar sesión para comentar.

Más respuestas (1)

Benjamin Kraus
Benjamin Kraus el 30 de Nov. de 2023
The issue with your current code is that on line 2 you need to initialize word2 as a character vector instead of a double vector.
Because you are initializing word2 as a double vector, when you attempt to assign a new value into the double vector, it is being cast into a double (even if you try to use a character instead).
word = string(input("Input: ","s"));
word2 = ''; % This needs to be a character vector (''), not a double vector ([]).
for n = char(97:122)
for x = 1:strlength(word)
if contains(word{1}(x:x),n)
word2(x) = n;
end
end
end
word = string(word2);
However, there are far easier ways to do what you are trying to do.
For example:
Option 1
word = input("Input: ","s"); % No cast to string
word2 = deblank(string(regexprep(word, '[^a-z]', ' '))); % Replace ' ' with '' to remove the letters.
Option 2
word = input("Input: ","s"); % No cast to string
word2 = word;
word2(word2<97|word2>122) = ' '; % Replace with [] to remove the letters.
word2 = deblank(word2);
Option 3
word = string(input("Input: ","s"));
word2 = deblank(replace(word, regexpPattern("[^a-z]")," "));
Option 4
word = string(input("Input: ","s"));
word2 = strjoin(extract(word, regexpPattern("[a-z]")), "");

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by