[英]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.