why do I get error "Unable to use a value of type string as an index.??"
조회 수: 259 (최근 30일)
이전 댓글 표시
I wrote a code but I keep getting this error:Unable to use a value of type string as an index., how is that?
%Accepts an input character array from the user and determines how
%many times a user-specified character appears within the character array.
%{
Define variables
strA_a-string
check_string- user-specified character
noccur-Number of time charU appears
%}
%Get a character array
strA_a=string(input('Enter a character array: ','s'));
%Get a user-specified character within the character array
check_string=string(input('Enter a specified character to check occurence: ','s'));
%Get the number of count c coours within A
noccur=count(strA_a,check_string);
%Tell the user
fprintf('the letter %c occurs %d times in the string.\n',check_string,noccur)
댓글 수: 0
답변 (1개)
Walter Roberson
2021년 3월 17일
편집: Walter Roberson
2021년 3월 17일
You probably accidentally assigned a value to a variable named count so that count() in your code is an indexing request instead of a function call.
(Or you might have done so in the past and you had not cleared your variables since then.)
Note:
The part of the instructions about accepting an input character array could be interpreted as expecting you to write a function that takes a parameter that is type char and which is not necessarily a character vector -- for example that it might be valid for the user to pass in
M = ['hi there';
'aminata ']
and that the counts are to be processed for that. If so, then be careful in your code:
MS = string(M)
count(MS, "t")
Notice the result of string() of a character array is one string entry per row of the character array, and that if you count() on a string array that the result is per string entry, not total.
참고 항목
카테고리
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!