我正在尝试编写一个程序,在单词之间插入空格以适应列宽,例如:
我已计算文本中的空格数量,然后计算出剩余的空格数量,并将其除以空格数量,以确定每个单词之间需要放多少个空格。这些剩余的空格将在主要的空格输入后均匀分布。
“主要的空格”是什么意思?
基本上,我想通过在单词之间添加空格来适应一个40个字符宽度的列,例如:“早上好,你好吗?”。 是否有可能做到这样?
- 您读入一行文本,例如:
早上好你怎么样?
- 您读入列宽,例如:
40
。 - 然后我已经数出了这个文本中有多少个空格(4个)。
- 现在我需要在这些单词之间分配剩余的空格,使文本长度为40。
Good morning how are you?
1234567890123456789012345678901234567890
当我尝试在单词之间插入空格时,遇到了问题,因为我不知道如何做。这是我目前的代码。
#include <stdio.h>
#include <string.h>
char text[65], spaces[50], ch;
int i, remainder, spacesr, count, column, length, distribution;
int main(){
i = 0;
count = 0;
printf("Please enter a line of text: ");
while(ch != '\n')
{
ch = getchar();
text[i]=ch;
i++;
}
text[i]='\0';
printf("Text: %s",text);
printf ("Please enter the width of the column: ");
scanf ("%d", &column);
for (i = 0; text[i] != '\0'; i++) {
if (text[i] == ' ') {
count++;
}
}
length = strlen(text);
spacesr = column - length;
distribution = spacesr / count;
remainder = spacesr % count;
if (length > column) {
printf ("ERROR: Length of text exceeds column width.");
}
}
我已计算文本中的空格数量,然后计算出剩余的空格数量,并将其除以空格数量,以确定每个单词之间需要放多少个空格。这些剩余的空格将在主要的空格输入后均匀分布。
“主要的空格”是什么意思?
基本上,我想通过在单词之间添加空格来适应一个40个字符宽度的列,例如:“早上好,你好吗?”。 是否有可能做到这样?
for (i = 0; text[i] != '\0'; i++) {
if (text[i] == ' ') {
then add a certain amount of spaces to it
main()
函数内部的局部变量;它们中没有一个需要成为全局变量。尽可能避免使用全局变量。有时候它们是必要的,并且是处理某些情况的最佳方式。然而,在编码的普通过程中,变量应该是在使用它们的函数内部的局部变量。 - Jonathan Leffler<string.h>
并使用strlen()
——这表明这些函数可以被使用。 - Jonathan Leffler