Как создать автоматическую новую строку? - PullRequest
0 голосов
/ 02 января 2019

Может ли кто-нибудь помочь мне создать анонимную функцию 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'

Ответы [ 2 ]

0 голосов
/ 02 января 2019

Вам нужна комбинация строковых функций для достижения этого результата.Программа ниже показывает, как это сделать.

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)

Выход программы проверен с переменным размером командного окна.

enter image description here

Larger Command Window

enter image description here

0 голосов
/ 02 января 2019

Для печати в Командном окне это предпочтение, которое можно установить на панели настроек в разделе

HOME> Настройки> Окно команд

preferences

Результат можно увидеть с помощью быстрого теста:

test

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...