필터 지우기
필터 지우기

How to align different lengths words/strings in fprintf?

조회 수: 54 (최근 30일)
gerway
gerway 2024년 1월 15일
댓글: Stephen23 2024년 1월 15일
I am attempting to output strings of varying lengths, including a mix of Chinese and English characters in different cases.(for example "aab"、"AABB_"、"不好玩") However, when I use MATLAB to format the output, I observe that even though I have set a fixed width for formatting , the displayed widths of different strings are not equal. This results in misalignment in the data display, as shown in the image below."
problems
How can i deal with this condition so that all strings can be displayed in equal width .
  댓글 수: 1
Stephen23
Stephen23 2024년 1월 15일
"How can i deal with this condition so that all strings can be displayed in equal width ."
You will need to use a fixed-width font.
It is clear from the posted screenshot that you are currently using a variable-width font. That will not work.

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

답변 (1개)

AMIT SURYAVANSHI
AMIT SURYAVANSHI 2024년 1월 15일
str1 = 'aab';
str2 = 'AABB_';
str3 = '不好玩';
fprintf('%-20s\n', str1);
aab
fprintf('%-20s\n', str2);
AABB_
fprintf('%-20s\n', str3);
不好玩
Character width variations can cause disparities in MATLAB strings' visual widths, particularly when combining languages such as Chinese and English. This may cause the output to be misaligned when formatting is attempted.
To overcome this issue, you can use the fprintf function with a fixed-width format specifier that accounts for the maximum intended visual width of the strings. For instance, to guarantee that the output string is left-justified within a field of 20 characters, use the%-20s format specifier:
In this manner, the misalignment problem should be reduced and every string will be left-justified in a field that is 20 characters wide.
You might need to modify the width depending on the exact characters and fonts used if your display is inconsistent and you have a mix of Chinese and English characters. It may take some trial and error to determine the right width in this situation for your particular situation.
It is not always possible to achieve precise alignment when merging languages with differing character widths since the actual visual width of characters might vary depending on the font and the characters themselves. Reduce misalignment by adjusting the width according to your unique use case and font selections.
  댓글 수: 1
gerway
gerway 2024년 1월 15일
I appreciate your response. However, due to constraints on the output length, I am unable to use formatting options like '%-20s' for alignment.

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

카테고리

Help CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by