How to align different lengths words/strings in fprintf?
72 ビュー (過去 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!