在Matlab中用新行替换字符串中的\n
我正在尝试将用新行分隔的字符串元胞数组合并为 Matlab 中的一个字符串。 以下方法合并字符串,但最终字符串包含 \n 而不是新行:
function str = toString(self)
% some not important logic that creates cell array called strings
% ...
str = '';
for i = 1 : 9
str = strcat(str, strings(i), '\n');
end
end
它返回: ' 111\n 111\n 111\n333666444555\n333666444555\n333666444555\n 222\n 222\n 222\n'
当我添加 str = sprintf(str);
在方法结束之前,会返回 Invalid format 错误。但是,当我写入 Matlab 命令窗口 sprintf(' 111\n 111\n 111\n333666444555\n333666444555\n333666444555\n 222\n 222\n 222\n');
它返回格式化字符串,但不任何错误。
任何人都知道可能有什么问题吗?为什么它在命令窗口中有效但在 .m 文件中无效?
I'm trying to merge cell-array of strings delimiting each by new line to one string in Matlab.
Following method merges the strings, but the final string contains \n instead of new lines:
function str = toString(self)
% some not important logic that creates cell array called strings
% ...
str = '';
for i = 1 : 9
str = strcat(str, strings(i), '\n');
end
end
It returns: ' 111\n 111\n 111\n333666444555\n333666444555\n333666444555\n 222\n 222\n 222\n'
When I add str = sprintf(str);
before the end of the method, it returns Invalid format error. However when I write to Matlab command window sprintf(' 111\n 111\n 111\n333666444555\n333666444555\n333666444555\n 222\n 222\n 222\n');
it returns formatted string without any errors.
Anyone knows what could be a problem? Why it works in command window but doesn't in .m file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
sprintf 将循环遍历元素或元胞数组:
循环的问题是 '\n' 是一个 2 元素字符数组,但您想要的是 sprintf('\n')
sprintf will loop over the elements or your cell array:
The problem with your loop is '\n' is a 2 element char array, but what you want is sprintf('\n')