C语言-书写长字符串时的换行方法

By: Ailson Jack Date: 2021.09.26 个人博客:http://www.only2fire.com/ 本文在我博客的地址是:http://www.only2fire.com/archives/139.html,排版更好,便于学习,也可以去我博客逛逛,兴许有你想要的内容呢。 在编写C程序时,如果想要打印某个字符串,而字符串的内容比较多,这就涉及到对这个长字符串进行书写换行,这里的换行并不会对最终的显示结果进行换行,只是为了阅读代码能够更加的清晰,不至于字符串的内容过长影响代码的阅读体验。

1.长字符串示例

/**

* @file test.c

* @author Ailson Jack (jackailson@foxmail.com)

* blog: www.only2fire.com

* @brief

* @version 1.0

* @date 2021-09-25

*

* @copyright Copyright (c) 2021

*

*/

#include

int main(void)

{

char name[] = "Ailson Jack";

int age = 18;

printf("Hello, My name is %s.\r\nI am %d years old this year.\r\nNice to meet you.\r\nCan I make friends with you?\r\nI like programming in C very much.\r\n", name, age);

while (1);

return 0;

}

上述代码需要打印的字符串内容比较长,在代码阅读软件中,可能需要拖动水平方向上的滚动条,才能看清楚字符串的完整内容,这极大的影响了代码的阅读效率。下图是上述代码的运行结果:

下面提供两种方法来将长字符串的单行书写变成多行书写。

2.书写长字符串的换行方法

方法一:利用双引号对长字符串进行换行

在对长字符串进行书写换行时,可以使用双引号将长字符串拆分成多个子字符串,编译器在编译处理时会自动的拼接这些子字符串,不会影响最终想要的显示效果,示例代码如下:

/**

* @file test.c

* @author Ailson Jack (jackailson@foxmail.com)

* blog: www.only2fire.com

* @brief

* @version 1.0

* @date 2021-09-25

*

* @copyright Copyright (c) 2021

*

*/

#include

int main(void)

{

char name[] = "Ailson Jack";

int age = 18;

printf("Hello, My name is %s.\r\nI am %d years old this year.\r\n"

"Nice to meet you.\r\nCan I make friends with you?\r\n"

"I like programming in C very much.\r\n", name, age);

while (1);

return 0;

}

上述示例的运行结果如下:

运行结果和长字符串未拆分时的效果一样。

方法二:利用反斜杠对长字符串进行换行

可以使用反斜杠对长字符串进行拆分,反斜杠后的换行符会被C忽略,所以可以拆分字符串,但是下一行的空格会被计算在内,这反斜杠拆分字符串的一个问题吧,示例代码如下:

/**

* @file test.c

* @author Ailson Jack (jackailson@foxmail.com)

* blog: www.only2fire.com

* @brief

* @version 1.0

* @date 2021-09-25

*

* @copyright Copyright (c) 2021

*

*/

#include

int main(void)

{

char name[] = "Ailson Jack";

int age = 18;

printf("Hello, My name is %s.\r\nI am %d years old this year.\r\n\

Nice to meet you.\r\nCan I make friends with you?\r\n\

I like programming in C very much.\r\n", name, age);

while (1);

return 0;

}

上述代码的运行结果如下图所示:

运行结果和最终想要的结果还是有差异的,插入了一些不需要的空格,因为反斜杠拆分的字符串会把下一行的空格也计算在内。

3.总结

对长字符串的书写换行,建议使用双引号进行拆分,这是最完美的,显示效果和最终想要的效果是一致的。

欢迎关注博主的公众号呀: 如果文中有什么问题欢迎指正,毕竟博主的水平有限。

如果这篇文章对你有帮助,记得点赞和关注博主就行了^_^。

排版更好的内容见我博客的地址:http://www.only2fire.com/archives/139.html

注:转载请注明出处,谢谢!^_^

Copyright © 2022 世界杯吉祥物_世界杯日本队 - ctpapi.com All Rights Reserved.