Array of ASCII Characters to String

16 views (last 30 days)
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.

Accepted Answer

Stephen23
Stephen23 on 30 Nov 2023
Edited: Stephen23 on 30 Nov 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 Comment
Steven Lord
Steven Lord on 30 Nov 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'

Sign in to comment.

More Answers (1)

Benjamin Kraus
Benjamin Kraus on 30 Nov 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]")), "");

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!