Hi cui xingxing,
I will address your questions one by one.
...these were introduced in R2017b onwards, do they have some applicable scenarios?
- matlab::data::String is the basic UTF-16 string type (std::basic_string<char16_t>) defned within the matlab::data namespace.
- matlab::data::MATLABString is an 'optional object' wrapped around matlab::data::String, allowing you to represent missing string values (For more information on 'optional' refer here: https://mathworks.com/help/matlab/apiref/matlab.data.optional.html). Use this when your string data might contain missing values that need to be preserved.
- matlab::engine::String is also a UTF-16 string type (std::basic_string<char16_t>) but belongs to the matlab::engine namespace. Use this when working with MATLAB engine functions, such as connecting to MATLAB sessions.
- factory.createArray<MATLABString>() is a factory method from matlab::data::ArrayFactory that creates arrays containing MATLABString elements. Use this when you need to create string arrays that can contain missing values.
...but "matlab::data::MATLABString" ,"matlab::data::String" how to convert to std::string each other?
Converting matlab::data::String to std::string:
matlab::data::String str_ml = get_some_string(); // your string here
std::string str(str_ml.begin(), str_ml.end());
Converting matlab::data::MATLABString to std::string:
matlab::data::MATLABString str_optional = get_some_string(); // your string here
if (str_optional.has_value()) {
matlab::data::String str_ml = str_optional;
std::string str(str_ml.begin(), str_ml.end());
// Handle missing value case
Important Note: The simple conversion method shown above only works correctly for ASCII characters. For proper UTF-16 to UTF-8 conversion with Unicode support, you would need additional conversion logic.
For more information, refer to the followng documentations:
- https://mathworks.com/help/matlab/apiref/matlab.data.string.html
- https://mathworks.com/help/matlab/apiref/matlab.data.matlabstring.html
- https://mathworks.com/help/matlab/apiref/matlab.data.optional.html
Hope this helps!