|
发表于 2024-3-12 08:39:25
|
显示全部楼层
好的,下面是一个稍微排列整齐一些的代码:
- #include <stdio.h>
- #include <string.h>
- void printAlignedText(char *text) {
- int len = strlen(text);
-
- // 去掉开头的空格
- while (text[0] == ' ') {
- text++;
- }
-
- // 统计单词数和最长单词长度
- int wordCount = 0;
- int maxLength = 0;
- for (int i = 0; i < len; i++) {
- if (text[i] != ' ') {
- maxLength++;
- } else {
- if (maxLength > 0) {
- wordCount++;
- maxLength = 0;
- }
- }
- }
-
- // 输出对齐后的文本
- int spaceCount = 0;
- for (int i = 0; i < len; i++) {
- if (text[i] != ' ') {
- printf("%c", text[i]);
- } else {
- if (maxLength > 0) {
- spaceCount = (20 - maxLength) / wordCount;
- for (int j = 0; j < spaceCount; j++) {
- printf(" ");
- }
- wordCount--;
- maxLength = 0;
- }
- }
- }
- }
- int main() {
- char text[100];
- printf("请输入要排列整齐的文本:");
- fgets(text, sizeof(text), stdin);
- text[strcspn(text, "\n")] = '\0'; // 去掉fgets函数读取的换行符
-
- printf("排列整齐后的文本为:\n");
- printAlignedText(text);
-
- return 0;
- }
复制代码
你可以输入一段文本,程序会将文本按每个单词之间有合适的空格对齐输出。例如,如果输入"Hello World!",程序会输出:
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|