필터 지우기
필터 지우기

Limit length of a string

조회 수: 28 (최근 30일)
Christian Günther
Christian Günther 2023년 1월 16일
답변: Christian Günther 2023년 1월 16일
Hello,
How can I limit the lengt of strings that I print out ?
text1 contains a sting of length 7 to 25, but I want to print a maximum of 18 charactes.
I have tried the following, but it does not work for text1:
text1='012345678901234567890123456789';
text2='01234567';
sprintf('%-18s',text1)
ans = '012345678901234567890123456789'
sprintf('%-18s',text2)
ans = '01234567 '
In the end it should look like a table.
Best regards
Christian

채택된 답변

Christian Günther
Christian Günther 2023년 1월 16일
Hello,
I've found the solution myself:
with this command it gests truncated to 18 characters:
sprintf('%+18.18s',text1)

추가 답변 (2개)

Matt J
Matt J 2023년 1월 16일
text1='012345678901234567890123456789';
text2='01234567';
text1(19:end)=''
text1 = '012345678901234567'
text2(19:end)=''
text2 = '01234567'
  댓글 수: 2
Christian Günther
Christian Günther 2023년 1월 16일
Hello,
Thanks for the reply.
It is working, but I need to overwrite each string before using it.
Thanks !!
Matt J
Matt J 2023년 1월 16일
편집: Matt J 2023년 1월 16일
Wrap the steps in some function,
text1='012345678901234567890123456789';
text2='01234567';
trunctext(text1)
012345678901234567
trunctext(text2)
01234567
function trunctext(T)
T(19:end)='';
disp(T)
end

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2023년 1월 16일
https://www.mathworks.com/help/matlab/ref/extractbefore.html
This can be used in an expression without modifying the variable. Also it can be used with string() objects as well
  댓글 수: 1
Christian Günther
Christian Günther 2023년 1월 16일
this is failing for text2:
text2='01234567';
sprintf('%+18s',extractBefore(text2,18))
% Error using extractBefore (line 51)
% Numeric value exceeds the number of characters in element 1.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by