[英]C program to format text
我得到一个字符串,单词之间有很多空格。 我必须编写一个程序,将给定的字符串转换为文本,每行不超过 80 个字符。 不应拆分任何词,必须使用 justify。 无需使用额外的库或函数! 我需要帮助解决这个问题。
Example input: "John had a lot of work to do."
Result:"John had
a lot of
work to
do"
在示例中,显然我没有使用 80 个字符规则,而是使用 8 个字符。到目前为止,我的代码消除了额外的空格并可以计算字符串的长度。
#include <stdio.h>
int main()
{
char text[1000], blank[1000],rez[1000];
int n,i;
printf("give string\n");
gets(text);
blankremove(text,blank);
printf("%s\n",blank);
n=lenght(blank);
printf("%d", n);
return 0;
}
int lenght(char a[]){
int lenght;
lenght=0;
while (a[lenght]!='\0')
{
lenght++;
}
return lenght;
}
int blankremove(char text[], char blank[])
{
int c = 0, d = 0;
while (text[c] != '\0') {
if (text[c] == ' ') {
int temp = c + 1;
if (text[temp] != '\0') {
while (text[temp] == ' ' && text[temp] != '\0') {
if (text[temp] == ' ') {
c++;
}
temp++;
}
}
}
blank[d] = text[c];
c++;
d++;
}
blank[d] = '\0';}
(这对我来说听起来像是家庭作业。请记住,老师也可以访问 Stackoverflow。)
让我们看看,您的格式是...令人遗憾,但这不是您要问的。
我认为这将满足您的需求。
在 main 中的 return 之前添加这些行:
fillLine(blank,rez,sizeof(rez));
printf("%s\n", rez);
然后创建一个名为 fillLine 的函数,该函数将查看适合的内容并将其放在线上(如果适合)。
/* Find the length of the next word on the line, upto the next space.
*/
int lenWord(char *in)
{
int ii;
for(ii=0; in[ii]!=0 && in[ii]!=' '; ii++);
return(ii);
}
#define MAX_COLUMNS 16
/*
* This will stuff what it can in MAX_COLUMNS columns
*/
int fillLine(char *blank, char *rez, int rezSize)
{
int in;
int out;
int col;
for(col=0, in=0, out=0; blank[in]!=0 && out<rezSize;) {
int len=lenWord(&blank[in]);
if(col+len+1 < MAX_COLUMNS ) {
int ii;
for(ii=0; ii<len; ii++) {
rez[out]=blank[in];
in++;
out++;
col++;
}
rez[out]=' ';
in++;
out++;
col++;
} else {
rez[out]='\n';
out++;
col=0;
}
}
return(out);
}
这个版本有一些问题(我建议你在提交之前解决):
rez
区域的大小传递给函数,但没有对其进行足够的检查,以确保我不会超出结尾并破坏其他东西。fillLine
函数可以与您的blankRemove
函数结合使用,使程序更加简洁。0!=in[ii]
而不是in[ii]!=0
。 这有助于避免if( in[ii]=0) {
的可能性。 有些人对尤达条件感到兴奋,无论是支持还是反对。这会给你的想法。 我可能会评论说,使用 ii 之类的变量而不是 i 可以更轻松地在文本编辑器中搜索它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.