Effacer les filtres
Effacer les filtres

How to align different lengths words/strings in fprintf?

54 vues (au cours des 30 derniers jours)
gerway
gerway le 15 Jan 2024
Commenté : Stephen23 le 15 Jan 2024
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 commentaire
Stephen23
Stephen23 le 15 Jan 2024
"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.

Connectez-vous pour commenter.

Réponses (1)

AMIT SURYAVANSHI
AMIT SURYAVANSHI le 15 Jan 2024
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 commentaire
gerway
gerway le 15 Jan 2024
I appreciate your response. However, due to constraints on the output length, I am unable to use formatting options like '%-20s' for alignment.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Types dans Help Center et File Exchange

Produits


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by