Array of ASCII Characters to String
18 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Stephen23
2023-11-30
编辑:Stephen23
2023-11-30
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!£%&*"
X = S{1}<97 | S{1}>122;
S{1}(X) = []
You could also use ISSTRPROP, or REGEXPREP, or various other approaches that do not require any loops.
1 个评论
Steven Lord
2023-11-30
I'm partial to isstrprop, as you mentioned in your last sentence, as it doesn't depend on "magic numbers".
S = "UPPERCASElowercase!£%&*"
lowercaseLetterLocations = isstrprop(S, "lower");
S{1}(lowercaseLetterLocations)
更多回答(1 个)
Benjamin Kraus
2023-11-30
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]")), "");
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!