字符串文本串联String Literal Concatenation

若要形成占用多行的字符串文本,则可以将两个字符串串联起来。To form string literals that take up more than one line, you can concatenate the two strings. 为此,请键入反斜杠,然后按 Return 键。To do this, type a backslash, then press the RETURN key. 反斜杠将使编译器忽略以下换行符。The backslash causes the compiler to ignore the following newline character. 例如,字符串文本For example, the string literal

"Long strings can be bro\  
ken into two or more pieces."  

等同于字符串is identical to the string

"Long strings can be broken into two or more pieces."  

在之前可能已使用过反斜杠后跟换行符的任何地方,都可以使用字符串串联,用来输入长于一行的字符串。String concatenation can be used anywhere you might previously have used a backslash followed by a newline character to enter strings longer than one line.

若要在字符串文本中强制换行,请在字符串中要换行的位置输入换行转义序列 (\n),如下所示:To force a new line within a string literal, enter the newline escape sequence (\n) at the point in the string where you want the line broken, as follows:

"Enter a number between 1 and 100\nOr press Return"  

由于字符串可以在源代码的任何列中开始,而长字符串可以在后面的行的任何列中继续,因此可以放置字符串以增强源代码可读性。Because strings can start in any column of the source code and long strings can be continued in any column of a succeeding line, you can position strings to enhance source-code readability. 在任一情况下,在输出时,字符串的屏幕表示形式都不受影响。In either case, their on-screen representation when output is unaffected. 例如:For example:

printf_s ( "This is the first half of the string, "  
           "this is the second half ") ;  

只要将字符串中的每个部分都用双引号括起来,则各个部分都将作为单个字符串进行串联和输出。As long as each part of the string is enclosed in double quotation marks, the parts are concatenated and output as a single string. 此串联根据转换阶段指定的编译期间的事件序列发生。This concatenation occurs according to the sequence of events during compilation specified by translation phases.

"This is the first half of the string, this is the second half"  

初始化为仅用空白分隔的两个不同的字符串文本的字符串指针将作为单个字符串存储(指针在指针声明中讨论)。A string pointer, initialized as two distinct string literals separated only by white space, is stored as a single string (pointers are discussed in Pointer Declarations). 当正确引用后(如以下示例所示),结果与上一示例的相同:When properly referenced, as in the following example, the result is identical to the previous example:

char *string = "This is the first half of the string, "  
               "this is the second half";  

printf_s( "%s" , string ) ;  

在翻译阶段 6 中,相邻字符串文本或相邻宽字符串文本的任意序列指定的多字节字符序列被串联为一个多字节字符序列。In translation phase 6, the multibyte-character sequences specified by any sequence of adjacent string literals or adjacent wide-string literals are concatenated into a single multibyte-character sequence. 因此,不要设计在执行期间允许修改字符串文本的程序。Therefore, do not design programs to allow modification of string literals during execution. ANSI C 标准规定,修改字符串的结果是不确定的。The ANSI C standard specifies that the result of modifying a string is undefined.

请参阅See Also

C 字符串文本C String Literals