sprintf - Format data into string or character vector (2024)

Format data into string or character vector

collapse all in page

Syntax

str = sprintf(formatSpec,A1,...,An)

[str,errmsg]= sprintf(formatSpec,A1,...,An)

str = sprintf(literalText)

Description

str = sprintf(formatSpec,A1,...,An) formats the data in arrays A1,...,An using the formatting operators specified by formatSpec and returns the resulting text in str. The sprintf function formats the values in A1,...,An in column order. If formatSpec is a string, then so is the output str. Otherwise, str is a character vector.

To return multiple pieces of formatted text as a string array or a cell array of character vectors, use the compose function.

example

[str,errmsg]= sprintf(formatSpec,A1,...,An) returns an error message as a character vector when the operation is unsuccessful. Otherwise, errmsg is empty.

str = sprintf(literalText) translates escape-character sequences in literalText, such as \n and \t. It returns all other characters unaltered. If literalText contain a formatting operator (such as %f), then str discards it and all characters after.

Examples

collapse all

Floating-Point Formats

Open Live Script

Format a floating-point number using %e, %f, and %g specifiers.

A = 1/eps;str_e = sprintf('%0.5e',A)
str_e = '4.50360e+15'
str_f = sprintf('%0.5f',A)
str_f = '4503599627370496.00000'
str_g = sprintf('%0.5g',A)
str_g = '4.5036e+15'

Literal Text and Array Inputs

Open Live Script

Combine literal text with array values to create a character vector.

str = 'The array is 2x3.'

Specify Formatted Text as String Array

Open Live Script

To return formatted text as a string, specify formatSpec as a string instead of a character vector when you call the sprintf function.

Convert data and return the result as a string.

formatSpec = "The current time is: %d:%d %s";A1 = 11;A2 = 20;A3 = 'a.m.';str = sprintf(formatSpec,A1,A2,A3)
str = "The current time is: 11:20 a.m."

Convert input string. Input arrays that contain text either can be character vectors or strings.

A1 = 2;A2 = 35;A3 = "p.m.";str = sprintf(formatSpec,A1,A2,A3)
str = "The current time is: 2:35 p.m."

Integer Format with Floating-Point Inputs

Open Live Script

Explicitly convert double-precision values to integers.

str = sprintf('%d',round(pi))
str = '3'

Specify Field Width of a Printed Value

Open Live Script

Specify the minimum width of the printed value.

str = sprintf('%025d',123456)
str = '0000000000000000000123456'

The 0 flag in the %025d format specifier requests leading zeros in the output.

Reorder Inputs Using Position Identifier (n$)

Open Live Script

Reorder the input values using the n$ position identifier.

A1 = 'X';A2 = 'Y';A3 = 'Z';formatSpec = ' %3$s %2$s %1$s';str = sprintf(formatSpec,A1,A2,A3)
str = ' Z Y X'

Create Character Vector from Values in Cell Array

Open Live Script

C = { 1, 2, 3 ; 'AA','BB','CC'};str = sprintf(' %d %s',C{:})
str = ' 1 AA 2 BB 3 CC'

The syntax C{:} creates a comma-separated list of arrays that contain the contents of each cell from C in column order. For example, C{1}==1 and C{2}=='AA'.

Input Arguments

collapse all

A1,...,AnNumeric, character, or string arrays
arrays

Numeric, character, or string arrays.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | string

literalTextInput text without formatting operators
character vector | string scalar

Input text without formatting operators, specified as a character vector or string scalar. sprintf translates any escape-character sequences in literalText.

Data Types: char | string

Output Arguments

collapse all

str — Formatted text
character vector | string scalar

Formatted text, returned as a character vector or a string scalar. The type of output matches the type of formatSpec.

errmsg — Error message
character vector

Error message, returned as a character vector, when the operation is unsuccessful. Otherwise, errmsg is empty.

Tips

  • The sprintf function is similar to fprintf, but fprintf prints to a file or to the Command Window.

  • Format specifiers for the reading functions sscanf and fscanf differfrom the formats for the writing functions sprintf and fprintf.The reading functions do not support a precision field. The widthfield specifies a minimum for writing, but a maximum for reading.

  • If you specify an invalid formatting operator or special character, then sprintf prints all text up to the invalid operator or character and discards the rest.

    Example: If formatSpec is 'value = %z', then sprintf prints 'value =' because %z is not a formatting operator.

    Example: If formatSpec is 'character \x99999 = %s', then sprintf prints 'character' because \x99999 is not a valid special character.

References

[1] Kernighan, B. W., and D. M. Ritchie, The C Programming Language, Second Edition, Prentice-Hall, Inc., 1988.

[2] ANSI specification X3.159-1989: “Programming Language C,” ANSI, 1430 Broadway, New York, NY 10018.

Extended Capabilities

Version History

Introduced before R2006a

See Also

char | fprintf | int2str | num2str | sscanf | fscanf | compose | string

Topics

  • Formatting Text

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

sprintf - Format data into string or character vector (1)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本 (日本語)
  • 한국 (한국어)

Contact your local office

sprintf - Format data into string or character vector (2024)

FAQs

What is a string or character vector? ›

A typical use is to store short pieces of text as character vectors, such as c = 'Hello World' . A string array is a container for pieces of text. String arrays provide a set of functions for working with text as data. You can create strings using double quotes, such as str = "Greetings friend" .

What is the format of sprintf? ›

The sprintf function formats and stores a series of characters and values in buffer . Each argument (if any) is converted and output according to the corresponding format specification in format . The format consists of ordinary characters and has the same form and function as the format argument for printf .

What does sprintf do in Matlab? ›

sprintf (MATLAB Functions) [s,errmsg] = sprintf(format,A,...) formats the data in matrix A (and in any additional matrix arguments) under control of the specified format string, and returns it in the MATLAB string variable s . The sprintf function returns an error message string errmsg if an error occurred.

What is %s %d in Matlab? ›

The format input '%s' designates that the first output will be character vectors separated by whitespace characters. '%d,' specifies that the second output will be signed integer values and ignoring ',' characters.

What is an example of a character vector? ›

As far as I know, what most languages call a string, R calls a character vector. For example, "Alice" is not a string, it's a character vector of length 1. Similarly, c("Alice", "Bob") is a character vector of length 2.

What is the difference between a string and a vector? ›

TLDR: string s are optimized to only contain character primitives, vector s can contain primitives or objects. The preeminent difference between vector and string is that vector can correctly contain objects, string works only on primitives.

Does sprintf return a string? ›

The Sprintf function returns the length of the string written to the destination variable (Dest). Up to 10 arguments can be passed into the Format string, with format specifiers corresponding one-to-one with the arguments. The function requires an argument for each format specifier.

Why not to use sprintf? ›

Sprintf to create a string unnecessarily involves extra processing and memory allocation for string formatting. This can have a performance impact, especially if the format string is used frequently or in performance-sensitive areas of the code.

Why use sprintf instead of printf? ›

Both generate a formatted string using some input (often a variable) and a format rule. The difference is that sprintf() returns the string; printf() echoes/prints the string. You can refer to the online php manual for details on sprintf() and printf().

What is the benefit of sprintf? ›

Sprintf() makes it possible to write formatted data into a string buffer. It is designed to accept a format string as its initial argument, prepending other arguments that specify what to write into the formatted string.

What is the difference between sprintf and Sprintf_s? ›

One main difference between sprintf_s and sprintf is that sprintf_s checks the format string for valid formatting characters, whereas sprintf only checks if the format string or buffer are NULL pointers. If either check fails, the invalid parameter handler is invoked, as described in Parameter validation.

Which functions are like sprintf? ›

sprintf
VariationSupportedPurpose
sprintf()Prints to a buffer, but snprintf is recommended to prevent overflowing the buffer.
snprintf()Prints to a buffer, recommended method.
vsprintf()Prints to a buffer, using va_list variable arguments.
vsnprintf()Prints to a buffer, using va_list variable arguments and buffer size.
4 more rows

What does %d mean in MATLAB? ›

%d represents signed integers (base 10). sprintf('John is %d years old', 7) % 'John is 7 years old' %f represents floating point numbers. sprintf('The first 8 dp of pi are %.8f', pi)

What is the floating-point data type? ›

A floating-point data type uses a formulaic representation of real numbers as an approximation so as to support a trade-off between range and precision. For this reason, floating-point computation is often found in systems which include very small and very large real numbers, which require fast processing times.

What is an example of a character string? ›

Strings are used for storing text/characters. For example, "Hello World" is a string of characters.

What is a vector character? ›

Character/string – each element in the vector is a string of one or more characters. Built in character vectors are letters and LETTERS which provide the 26 lower (and upper) case letters, respecitively.

How do you define a vector string? ›

Syntax for Vectors in C++

Every new vector must be declared starting with the vector keyword. This is followed by angle brackets which contain the the type of data the vector can accept like strings, integers, and so on. Lastly, the vector name - we can call this whatever we want.

What is a character string variable? ›

A character-string value is a sequence of characters. The number of characters in a sequence is called the length of the sequence. In Open PL/I, the maximum length of a string value is 32767 bytes or characters. A character-string of zero length is called a null string.

Top Articles
Healthy Tuna Noodle Casserole Recipe
Vegan shepherd's pie | Vegetables recipes | Jamie Oliver
Fighter Torso Ornament Kit
Kevin Cox Picks
Stadium Seats Near Me
How To Be A Reseller: Heather Hooks Is Hooked On Pickin’ - Seeking Connection: Life Is Like A Crossword Puzzle
Acts 16 Nkjv
Nation Hearing Near Me
Hssn Broadcasts
Aktuelle Fahrzeuge von Autohaus Schlögl GmbH & Co. KG in Traunreut
Clarksburg Wv Craigslist Personals
Shreveport Active 911
Dr Adj Redist Cadv Prin Amex Charge
Zalog Forum
Sni 35 Wiring Diagram
Little Caesars 92Nd And Pecos
Best Mechanics Near You - Brake Masters Auto Repair Shops
Georgetown 10 Day Weather
Marine Forecast Sandy Hook To Manasquan Inlet
Timeforce Choctaw
[PDF] NAVY RESERVE PERSONNEL MANUAL - Free Download PDF
Albert Einstein Sdn 2023
Roanoke Skipthegames Com
55Th And Kedzie Elite Staffing
Temu Seat Covers
Shia Prayer Times Houston
Craftsman Yt3000 Oil Capacity
The Bold and the Beautiful
Moonrise Time Tonight Near Me
Mrstryst
60 Second Burger Run Unblocked
Att U Verse Outage Map
Lil Durk's Brother DThang Killed in Harvey, Illinois, ME Confirms
Oreillys Federal And Evans
Caderno 2 Aulas Medicina - Matemática
Bitchinbubba Face
Admissions - New York Conservatory for Dramatic Arts
Craiglist Hollywood
Second Chance Apartments, 2nd Chance Apartments Locators for Bad Credit
Fetus Munchers 1 & 2
Mississippi weather man flees studio during tornado - video
Leland Nc Craigslist
Mother Cabrini, the First American Saint of the Catholic Church
Youravon Com Mi Cuenta
Menu Forest Lake – The Grillium Restaurant
Sky Dental Cartersville
8 4 Study Guide And Intervention Trigonometry
Random Warzone 2 Loadout Generator
Shiftselect Carolinas
Julies Freebies Instant Win
The Plug Las Vegas Dispensary
Congressional hopeful Aisha Mills sees district as an economical model
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 5364

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.