Why would command syntax split string when using double quotes?
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
disp 'str ing' % good
disp "str ing" % error, Too many input arguments
I am on R2020a. It seems that the latter is equivalent to
disp str ing
I thought, at least
disp "str ing"
should be interpreted as
disp('"str ing"')
why would matlab split the string into several parts?
채택된 답변
Not exactly. The latter is equivalent to disp('"str', 'ing"')
N 'str ing'
nargin = 1
varargin{1} =
str ing
N "str ing"
nargin = 2
varargin{1} =
"str
varargin{2} =
ing"
function N(varargin)
fprintf('nargin = %d\n', nargin);
celldisp(varargin)
end
why would matlab split the string into several parts?
Because that is what is documented:
With command syntax, MATLAB passes all inputs as character vectors (that is, as if they were enclosed in single quotation marks) and does not assign outputs to variables. To pass a data type other than a character vector, use the function syntax. To pass a value that contains a space, you have two options. One is to use function syntax. The other is to put single quotes around the value. Otherwise, MATLAB treats the space as splitting your value into multiple inputs.
In order for disp "str ing" to be treated as disp("str ing") then that would directly violate the rule that MATLAB passes all inputs as character vectors.
It does not explain why MATLAB does not convert the string into a character vector, as-if disp('str ing') had been called, but the documentation never implies anything like that would happen. Instead, the documentation talks only about single-quotes to include blanks, not about double-quotes.
It would not be unreasonable for MATLAB to be enhanced to handle double-quoted strings... but it is not a bug that it does not do so at the moment.
댓글 수: 5
Xingwang Yong
2021년 10월 28일
편집: Xingwang Yong
2021년 10월 28일
In function syntax, double quotes and single quotes make no difference, i.e. disp("str ing") == disp('str ing'). I thought they would be the same in command syntax, which is not the case though. Although documented, this is counterintuitive.
It is not correct that single quotes or double quotes make no difference. Consider
N('str ing')
numel = 7
#1: s
#2: t
#3: r
#4:
#5: i
#6: n
#7: g
N("str ing")
numel = 1
#1: str ing
function N(S)
NE = numel(S);
fprintf('numel = %d\n', NE);
for K = 1 : NE
fprintf('#%d: %s\n', K, S(K));
end
end
Character vectors with single quotes are not the same as string objects with double quotes
" In function syntax, double quotes and single quotes make no difference,"
No, strings and character arrays are very different things:
str = "not the same things";
chr = 'not the same things';
numel(str)
ans = 1
numel(chr)
ans = 19
double(str)
ans = NaN
double(chr)
ans = 1×19
110 111 116 32 116 104 101 32 115 97 109 101 32 116 104 105 110 103 115
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
"this is counterintuitive."
Not once you appreciate the fact the strings are a container class and have very different properties to character arrays. It seems that most confusion comes from users who attempt to smush them together into one great big mushy "I can use string and character arrays interchangeably everywhere"-class.
We (MathWorks) went to a good bit of effort to make sure that functions that supported char row vectors prior to the introduction of string arrays behaved 'sensibly' (waving my hands a little bit) when passed in string scalars. It is true that there are some functions that behave differently; length, size, numel, and class are notable functions in this category.
f = @(x) cell2table({length(x), size(x), numel(x), class(x)}, ...
VariableNames = ["length", "size", "numel", "class"]);
charResults = f('MATLAB')
charResults = 1×4 table
length size numel class
______ ______ _____ ________
6 1 6 6 {'char'}
stringResults = f("MATLAB")
stringResults = 1×4 table
length size numel class
______ ______ _____ __________
1 1 1 1 {'string'}
But if you want to call for example something like strlength that 'knows' what to do with char vectors and strings, it returns a sensible answer on both char row vectors and scalar strings.
[strlength('MATLAB'), strlength("MATLAB")]
ans = 1×2
6 6
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Command form is another place where the behavior does differ. I don't remember off the top of my head when this was discussed (and that discussion may have happened above my pay grade and/or among a different subset of MathWorks development than the design discussions I participate in) but I would be mildly surprised if it hadn't been discussed. Backwards compatiblity (not changing the behavior of commands that already accepted text including double quotes and treated those double quotes as part of the data rather than part of the syntax) might have factored into those discussions and the decision.
And then there is the behavior with (overloaded) operators, where they diverge quite significantly.
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
