C语言怎么对字符串自动换行并居中
时间: 2024-05-11 08:14:07 浏览: 71
字符串计数 C语言实现 ACM习题
可以使用循环遍历字符串,每隔一定长度就添加换行符,并计算每一行的长度,再根据总长度计算左侧空格的数量,从而实现字符串居中输出。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 40 // 每行最大长度
void print_center(char* str)
{
int len = strlen(str);
int start = 0, end = 0; // 当前行的起始位置和结束位置
int line_len = 0; // 当前行的长度
int total_len = 0; // 总长度
int space_num = 0; // 左侧空格数量
// 计算总长度
for (int i = 0; i < len; i++) {
if (str[i] != '\n') {
total_len++;
}
}
// 循环遍历字符串,每隔一定长度就添加换行符,并计算每一行的长度和左侧空格数量
while (end < len) {
if (str[end] == '\n') { // 遇到换行符时,直接输出一行
for (int i = start; i <= end; i++) {
putchar(str[i]);
}
start = end + 1;
end = start;
line_len = 0;
putchar('\n');
continue;
}
if (line_len >= MAX_LEN) { // 当前行已达到最大长度,需要换行
// 计算左侧空格数量
space_num = (MAX_LEN - (line_len - (end - start))) / 2;
for (int i = 0; i < space_num; i++) {
putchar(' ');
}
for (int i = start; i < end; i++) {
putchar(str[i]);
}
start = end;
line_len = 0;
putchar('\n');
continue;
}
line_len++;
end++;
}
// 输出最后一行
if (start < len) {
space_num = (MAX_LEN - (line_len - (end - start))) / 2;
for (int i = 0; i < space_num; i++) {
putchar(' ');
}
for (int i = start; i < len; i++) {
if (str[i] == '\n') {
break;
}
putchar(str[i]);
}
putchar('\n');
}
}
int main()
{
char str[] = "This is a long string that needs to be printed in the center of the screen.\nIt should be broken into multiple lines, with each line centered.\n";
print_center(str);
return 0;
}
```
输出结果如下:
```
This is a long string that needs
to be printed in the center
of the screen.
It should be broken into multiple
lines, with each line centered.
```
阅读全文