Insert desired number of spaces in the string contains numerical value

93 vues (au cours des 30 derniers jours)
Bhaskar R
Bhaskar R le 14 Août 2019
Modifié(e) : Bhaskar R le 14 Août 2019
Hi,
I need to print the below string which is in loop as
0 STR 1
where the first character is zero then 30 spaces then string STR and numerical 1 after five spaces
for this i wrote the statement as
txt = sprintf('0%30sSTR%5s%d',1);
But answer is not expected as above it gave the result as below
txt =
'0 STR'
  2 commentaires
Guillaume
Guillaume le 14 Août 2019
It's not entirely clear what you want and your example is lacking since your format string has three format specifiers (two strings and a decimal), yet you only give it one number.
  • Is STR an input (i.e. it can be some other string) or a fixed part of the format?
  • If it's actually an input does the 30 space change depending on the length of the input or is it fixed regardless?
  • Similarly, is the 5 spacing dependent on the number of digits in the number (i.e. 2 digits = spacing of 4, 3 digits = spacing of 3, etc.)?
Bhaskar R
Bhaskar R le 14 Août 2019
Modifié(e) : Bhaskar R le 14 Août 2019
Guillaume, only decimal part changes
  • STR is not an input it is a fixed part
  • 30 spaces also a fixed part
  • 5 spaces also fixed
Only last one is decimal value it may varies as single or multiple digits
Note: first character zero is fixed
-Thanks

Connectez-vous pour commenter.

Réponse acceptée

Guillaume
Guillaume le 14 Août 2019
The clearest way to achieve what you want is to put the spaces explicitly in your format string:
txt = sprintf('0 STR %d', istep)
or construct it explicitly:
txt = sprintf(['0', blanks(30), 'STR', blanks(5), '%d'], istep)
You could also use the format string that you've specified, by giving it spaces for the string formats:
txt = sprintf('0%30sSTR%5s%d', ' ', ' ', istep);
But in my opinion, it's less clear as to the intent than the other two options.
  1 commentaire
Bhaskar R
Bhaskar R le 14 Août 2019
Modifié(e) : Bhaskar R le 14 Août 2019
Yeah, its worked(3rd one required)
Thanks :-)

Connectez-vous pour commenter.

Plus de réponses (1)

Matt J
Matt J le 14 Août 2019
How about
txt="0 STR "+1

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by