有人可以帮我创建一个匿名函数format_this(txt)
来格式化文本,以便用换行符替换靠近命令窗口边缘的空白-本质上是“漂亮打印”吗? 不一定必须是完美的(事实上,不需要成为匿名函数),但是我找不到如此奇怪的东西。
这就是我所拥有的:
txt='the quick brown fox jumps over the lazy dog';
txt=[txt ' ' txt ' ' txt]; %make longer
w=getfield(get(0,'CommandWindowSize'),{1}); %command window width
space_pos=strfind(txt,' '); %find space positions
wrap_x_times= (w:w:size(txt,2))); %estimate of many times the text should wrap to a newline
format_this=@(txt) txt;
%something like an ideal output:
disp(format_this(txt)) %example for super-small window
ans =
'the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog'
答案 0 :(得分:2)
答案 1 :(得分:2)
您需要组合字符串函数才能实现该结果。下面的程序显示了如何执行此操作。
clc
% the text
txt='the quick brown fox jumps over the lazy dog';
% makethe text a bit longer
txt=[txt ' ' txt ' ' txt];
% get the command window width
w=getfield(get(0,'CommandWindowSize'),{1});
% get the length of the text
txt_len = numel(txt);
% check if the length of text is exactly divisible
% by the size of window (w) or not
if(mod(txt_len, w)~= 0)
% if not, then get the number of
% characters required to make it a
% multiple of w
diff_n = w - mod(txt_len, w);
% append that many spaces to the end of the string
txt(end+1 : end+diff_n) = ' ';
end
% create an anoymous function
% step 1 - Split the array in multiple of size w into a cell array
% using reshape() and cellstr() function respectively
% step 2 - concatenate the newline character \n at the end of each
% element of the cell array using strcat()
% step 4 - join the cell array elements in a single string usin join()
format_this = @(txt)join(strcat(cellstr(reshape(txt,w, [])'), '\n'));
% get the formatted string as a 1-d cell array
formatted_str = format_this(txt);
% print the string to ft
ft = sprintf(formatted_str{1});
% display the ft
disp(ft)
程序输出已通过命令窗口的可变大小进行测试。