How to align different lengths words/strings in fprintf?
조회 수: 71 (최근 30일)
이전 댓글 표시
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."
How can i deal with this condition so that all strings can be displayed in equal width .
댓글 수: 1
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
2024년 1월 15일
str1 = 'aab';
str2 = 'AABB_';
str3 = '不好玩';
fprintf('%-20s\n', str1);
fprintf('%-20s\n', str2);
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!