Main Content

Sprintf

将数据格式化为字符串或字符向量

Description

例子

str= sprintf(FormatSpec,,,,一种1,...,AnFormats the data in arrays一种1,...,Anusing the formatting operators specified byFormatSpec并返回结果文字str。这SprintfFunction formats the values in一种1,...,An按列顺序。如果FormatSpec是字符串,然后输出也是str。Otherwise,str是一种character vector.

返回多个块格式化文本的年代tring array or a cell array of character vectors, use the撰写功能。

[[str,,,,errmsg] = sprintf(FormatSpec,,,,一种1,...,An返回一种nerror message as a character vector when the operation is unsuccessful. Otherwise,errmsg是empty.

str= sprintf(literalTexttranslates escape-character sequences inliteralText, 如\n一种nd\t。It returns all other characters unaltered. IfliteralTextcontain a formatting operator (such as%F),,,,thenstrdiscards it and all characters after.

Examples

全部收缩

为了mat a floating-point number using%e,,,,%F,,,,一种nd%G指定器。

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

将文字文本与数组值相结合以创建字符向量。

FormatSpec =“阵列为%dx%d。”; A1 = 2; A2 = 3; str = sprintf(formatSpec,A1,A2)
str = 'The array is 2x3.'

To return formatted text as a string, specifyFormatSpec作为字符串,而不是字符向量Sprintf功能。

Starting in R2017a, you can create strings using double quotes. 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."

Explicitly convert double-precision values to integers.

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

Specify the minimum width of the printed value.

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

0Flag in the%025dFormat specifier requests leading zeros in the output.

使用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'
C= { 1, 2, 3 ;'AA',,,,'BB',,,,'CC'}; str = sprintf('%d%s',,,,C{:})
str = ' 1 AA 2 BB 3 CC'

语法C{:}creates a comma-separated list of arrays that contain the contents of each cell fromC按列顺序。例如,c {1} == 1一种ndC{2}=='AA'

输入参数

全部收缩

为了mat of the output fields, specified using formatting operators.FormatSpec还可以包括普通文字和特殊字符。

如果FormatSpec包括代表逃生字符的文字,例如\n, 然后Sprintf翻译逃生角色。

FormatSpeccan be a character vector in single quotes, or, starting in R2016b, a string scalar.

为了matting Operator

一种Formatting operator starts with a percent sign,%GydF4y2Ba,并以转换字符结尾。需要转换字符。可选地,您可以指定标识符,标志,字段宽度,精度和子类型运算符%GydF4y2Ba一种nd the conversion character. (Spaces are invalid between operators and are shown here only for readability).

Conversion Character

This table shows conversion characters to format numeric and character data as text.

Value Type Conversion Details

Integer, signed

%dor%一世

Base 10

Integer, unsigned

%u

Base 10

%o

基地8(八分之一)

%X

Base 16 (hexadecimal), lowercase letters一种-F

%X

如同%X,,,,uppercase letters一种-F

浮点数

%F

Fixed-point notation (Use a precision operator to specify the number of digits after the decimal point.)

%e

Exponential notation, such as3.141593e+00(Use a precision operator to specify the number of digits after the decimal point.)

%e

如同%e,,,,but uppercase, such as3.141593E+00(Use a precision operator to specify the number of digits after the decimal point.)

%G

更紧凑%eor%F, 和no trailing zeros (Use a precision operator to specify the number of significant digits.)

%G

更紧凑%eor%F, 和no trailing zeros (Use a precision operator to specify the number of significant digits.)

Characters or strings

%C

Single character

%s

Character vector or string array. The type of the output text is the same as the type ofFormatSpec

Optional Operators

可选标识符,标志,字段宽度,精度和子类型操作员进一步定义了输出文本的格式。

  • Identifier

    订单处理函数输入参数。使用语法n$,,,,wherenrepresents the positions of the other input arguments in the function call.

    Example:('%3$s %2$s %1$s %2$s','A','B','C')prints input arguments'A',,,,'B',,,,'C'作为Follows:CB A B

    笔记:如果一种ninput argument is an array, you cannot use identifiers to specify particular array elements from that input argument.

  • Flags

    ' - '

    左侧。
    Example:%-5.2f
    Example:%-10s

    '+'

    始终为任何数字值打印一个符号字符(+或 - )。
    Example:%+5.2f
    Right-justify text.
    Example:%+10s

    ' '

    Insert a space before the value.
    Example:%5.2F

    '0'

    在值之前,用零以零为单位宽度。
    Example:%05.2F

    '//www.tatmou.com/de/help/matlab/ref/#'

    Modify selected numeric conversions:

    • 为了%o,,,,%X,,,,or%X, 打印0,,,,0x,,,,or0Xprefix.

    • 为了%F,,,,%e,,,,or%e, 打印decimal point even when precision is 0.

    • 为了%Gor%G,,,,do not remove trailing zeros or decimal point.

    Example:%#5.0F

  • Field Width

    要打印的字符数量最少。字段宽度运算符可以是一个数字,也可以是星号(*)参考输入参数。

    When you specify*作为the field width operator, the other input arguments must provide both a width and a value to be printed. Widths and values can be pairs of arguments or pairs within a numeric array. With*作为字段宽度运算符,您可以用不同的宽度打印不同的值。

    Example:这input arguments('%12d',intmax)等同于('%*d',12,intmax)

    Example:这input arguments('%*d',[2 10 5 100])return'10 100', 和two spaces allocated for10一种nd five spaces for100。一种s an alternative, you also can specify the field widths and values as multiple arguments, as in('%*D',2,10,5,100)

    这Function pads to field width with spaces before the value unless otherwise specified by flags.

  • 精确

    为了%F,,,,%e,,,,or%e

    number of digits to the right of the decimal point
    Example:'%.4f'printspi作为'3.1416'

    为了%Gor%G

    大数的数量
    Example:'%.4g'printspi作为'3.142'

    精密操作员可以是一个数字,也可以是星号(*)指参数。

    When you specify*领域精密操作,另一个输入rguments must provide both a precision and a value to be printed. Precisions and values can be pairs of arguments, or pairs within a numeric array. With*作为精确操作员,您可以将不同的值打印到不同的精度。

    When you specify*。*作为Field width and precision operators, you must specify field widths, precisions, and values as triplets.

    Example:这input arguments('%.4f',pi)等同于('%.*f',4,pi)

    Example:这input arguments('%6.4f',pi)等同于('%。*f',6,4,pi)

    Example:这input arguments('%*。*f',6,4,pi,9,6,exp(1))return'3.1416 2.718282', 和9一种nd6作为场宽度和输出的精度exp(1)

    笔记

    如果您为超过输入数字数据类型的精度的浮点值指定精度运算符,则结果可能与您指定的精度不匹配输入值。结果取决于您的计算机硬件和操作系统。

  • Subtypes

    You can use a subtype operator to print a floating-point value as its octal, decimal, or hexadecimal value. The subtype operator immediately precedes the conversion character. This table shows the conversions that can use subtypes.

    输入值类型

    Subtype and Conversion Character

    Output Value Type

    浮点数

    %bxor%bX
    %bo
    %bu

    双精度十六进制,八分或十进制价值
    Example:%bxprintspi作为400921fb54442d18

    %txor%tX
    %to
    %tu

    单位十六进制,八分或十进制值
    Example:%txprintspi作为40490fdb

格式运算符之前或之后的文本

FormatSpeccan also include additional text before a percent sign,%GydF4y2Ba,,,,or after a conversion character. The text can be:

  • Ordinary text to print.

  • Special characters that you cannot enter as ordinary text. This table shows how to represent special characters inFormatSpec

    Special Character

    表示

    Single quotation mark

    ''

    Percent character

    %%

    后斜线

    \\

    一种larm

    \a

    backspace

    \b

    形式饲料

    \f

    新队

    \n

    C一种rriage return

    \r

    Horizontal tab

    \t

    Vertical tab

    \v

    Character whose Unicode®数值可以由十六进制数表示,n

    \ xn

    Example:sprintf('\ x5a')返回'Z'

    字符的unicode数字值可以用八进制数表示,n

    \N

    Example:Sprintf('\132')返回'Z'

notable Behavior of Conversions with Formatting Operators

  • numeric conversions print only the real component of complex numbers.

  • 如果指定不符合数据的转换,例如数字值的文本转换,MATLAB®覆盖指定的转换,并使用%e

    Example:'%s'convertspito3.141593e+00

  • 如果you apply a text conversion (either%Cor%s)to integer values, MATLAB converts values that correspond to valid character codes to characters.

    Example:'%s'converts[65 66 67]toABC

numeric, character, or string arrays.

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

输入文本不格式化运算符,指定为字符向量或字符串标量。Sprintf翻译任何逃生字符序列literalText

Data Types:char|string

Output Arguments

全部收缩

为了matted text, returned as a character vector or a string scalar. The type of output matches the type ofFormatSpec

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

Tips

  • SprintfFunction is similar toFprintf,,,,butFprintfprints to a file or to the Command Window.

  • 为了mat specifiers for the reading functionssscanf一种ndfscanfdiffer from the formats for the writing functionsSprintf一种ndFprintf。阅读功能不支持精度字段。金宝app宽度字段指定写作的最低限度,但最大的阅读。

  • 如果指定无效格式操作员或特殊字符,则Sprintfprints all text up to the invalid operator or character and discards the rest.

    Example:如果FormatSpec'value = %z', 然后Sprintfprints'value ='因为%z不是格式操作员。

    Example:如果FormatSpec'角色\ x99999 =%s', 然后Sprintfprints'特点'因为\ x99999是not a valid special character.

References

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

[2] ANSI规范x3.159 - 1989:“编程L一种nguage C,” ANSI, 1430 Broadway, New York, NY 10018.

Extended Capabilities

Introduced before R2006a