Array of ASCII Characters to String

조회 수: 20 (최근 30일)
Parker
Parker 2023년 11월 30일
댓글: Steven Lord 2023년 11월 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