Taking a string from a string array then identifying the characters within that string

조회 수: 17 (최근 30일)
Hey guys, im relatively new to matlab and im trying to do my hangman assignment and im trying to identify the letters within a word strng. I understand that you can use the code;
A = ('word')
A(1) = w
However since I need to pull one word from a wide range of words I've decided to set up a string array. Pulling words out of my array works no problems although when I try and locate the position of certain letters in the string that i pulled from the array it just gives the same word. I'm prettu sure that when pulling the string of words out of the string array matlab then reccognises the string I pulled out as a string of length 1, anyway heres my code;
word_bank = ["aisle","cope","light","bucket","tail","eavesdrop";
"case","action","cruel","charge","crystal","acceptable";
"photography","discuss","marine","dog","cheese","matlab"];
r=randi([1 18],1);
str=(word_bank(r))
disp(str(1))

답변 (1개)

Stephen23
Stephen23 2021년 4월 28일
편집: Stephen23 2021년 4월 28일
A string array is a container class: it contains character vectors. Use curly braces to get the character vectors:
w = ["aisle","cope","light","bucket","tail","eavesdrop"; "case","action","cruel","charge","crystal","acceptable"; "photography","discuss","marine","dog","cheese","matlab"]
w = 3×6 string array
"aisle" "cope" "light" "bucket" "tail" "eavesdrop" "case" "action" "cruel" "charge" "crystal" "acceptable" "photography" "discuss" "marine" "dog" "cheese" "matlab"
r = randi(numel(w),1);
c = w{r} % get the character vector
c = 'charge'
c(1) % first character
ans = 'c'
w{r}(3) % third character
ans = 'a'

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by