why do I get error "Unable to use a value of type string as an index.??"
247 次查看(过去 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!