text data type, string data type

Yevgeny Gayev el 12 de Dic. de 2022
Actividad más reciente Edición por Giles a las el 10 de Dic. de 2024

There are two kinds of text data type (=string data type) in MATLAB:
Text1='aText'; % first one
Text2="aText"; % first one
The second one did not exist in "old" MATLAB versions but the first one only.
My questions are: 1) What was motivation of MathWorks programmers to introduce the Text Data Type of the second format?
Yes, I know the difference: length(Text1)=5 whilst length(Text2)=1; Text1(2)='T' but Text2(2) does not exist. The array Text3=['one' ; 'fifth'] does not exist too.
2) However, any explanations and recommendations how to apply the second sort in contrast to the first one?
3) Is there any way how to convert one sort to another one?
Thanks for explanation in advance!
Giles
Giles el 10 de Dic. de 2024 (Editada a las el 10 de Dic. de 2024)
There are a few benefits to " " strings--e.g. you can manipulate them as whole elements, so if you do a for loop with them you can just do:
for x = ["a" "b" "c"]
whereas with ' ' strings which must be grouped in a cell array the for loop actually steps across cells and you need to additionally extract the string from the cell before you get it:
for x = {'a' 'b' 'c'}, x = x{1};
Also " " strings allow useful behaviour like "hello"+2 -> "hello2", whereas if you try that with a ' ' string you get the character corresponding to ASCII code 2 appended. And various other useful ways of using " " strings with the + operator.
Basically " " strings are specialized for working with the strings as wholes, whereas ' ' strings are specialized for working with the characters in the string. (Though note you can get at characters in a " " string by adding in some {} syntax like this:
x = "hello", x{1}(1) -> 'h'
It's all a bit messy and I feel like MathWorks could have figured out a simpler way, but who knows. The only complaint I really have is that calling " " strings, where ' ' used to be called strings, is very confusing. They should have just called it the text data type, and left the word string to mean what it always meant, i.e. character vectors.
Jeff Alderson
Jeff Alderson el 12 de Dic. de 2022 (Editada a las el 21 de Feb. de 2023)
Please read this article for a more detailed explanation of the differences between character arrays and strings.
Yevgeny Gayev
2
Publicación
6
Responder