Array of ASCII Characters to String

17 次查看(过去 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.

采纳的回答

Stephen23
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!£%&*"
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 个评论
Steven Lord
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!£%&*"
S = "UPPERCASElowercase!£%&*"
lowercaseLetterLocations = isstrprop(S, "lower");
S{1}(lowercaseLetterLocations)
ans = 'lowercase'

请先登录,再进行评论。

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by