程序要求是:
(1)分别统计出其中英文字母数和空格数及整篇文章总字数;
(2)统计某一字符串在文章中出现的次数,并输出该次数;
(3)删除某一子串,并将后面的字符前移。
如果输入的文章刚好只有一行的话这个程序能够正常跑起来,但如果字数多了在调试界面上变成两行以上后,从第二行开始就会被当成要统计并删除的字符串,然后第一行以后的文章就没了(就像图片这样,调行数没用,还是这样,下面是我们使用的代码)
哪位可以解答一下,万分感谢!
#include <stdio.h>
#include<string.h>
#define MAX_LINES 100
#define MAX_CHARS_PER_LINE 80
typedef struct
{ char lines[MAX_LINES][MAX_CHARS_PER_LINE + 1];//记录文章字符数据
int numLines; //记录文章行数行数
} Article; //定义文章线性表
void countCharsAndSpaces(Article article) //计算文章
{
int totalChars = 0, totalSpaces = 0; // 字符,空格
int totalLetters = 0, totalDigits = 0; //字母,数字
for (int i = 0; i < article.numLines; i++)
{
char *line = article.lines[i]; //取出线性表中的字符
int lineLength = strlen(line);//文章总字符数存于lineLength
for (int j = 0; j < lineLength; j++)
{
if (line[j] >= 'a' && line[j] <= 'z' || line[j] >= 'A' && line[j] <= 'Z') //计算字母
{ totalLetters++; }
else if (line[j] >= '0' && line[j] <= '9') //计算数字
{ totalDigits++; }
else if (line[j] == ' ') //计算空格
{ totalSpaces++; }
}
totalChars += lineLength; printf("%s\n", line); //总字符数
}
printf("全部字母数: %d\n", totalLetters);
printf("数字个数: %d\n", totalDigits);
printf("空格个数: %d\n", totalSpaces);
printf("文章总字数: %d\n", totalChars);
}
int countSubstringOccurrences(Article article, char *substring) // 统计某字符串
{
int occurrences = 0; //计数
for (int i = 0; i < article.numLines; i++)
{
char *line = article.lines[i];
int lineLength = strlen(line);
for (int j = 0; j < lineLength; j++)
{
if (strncmp(&line[j], substring, strlen(substring)) == 0)//一一比较
{ occurrences++; }
}
}
return occurrences;
}
void removeSubstring(Article *article, char *substring)//删除 选定字符
{
for (int i = 0; i < article->numLines; i++)
{
char *line = article->lines[i];
int lineLength = strlen(line);
for(int j=0;j<lineLength;j++)
{
char *substringPos = strstr(line, substring); //查找该串位置
if (substringPos != NULL)
{
memmove(substringPos, &substringPos[strlen(substring)], lineLength - (substringPos - line)); //删除该串并且减少长度
}
}
printf("%s\n", line);
}
}
int main()
{
Article article;
char substring[MAX_CHARS_PER_LINE + 1];
printf("请输入文章的行数(不超过%d):", MAX_LINES);
scanf("%d", &article.numLines);
getchar(); // 消耗掉输入行数后的换行符
printf("请输入文章内容:\n");
for (int i = 0; i < article.numLines; i++)
{
fgets(article.lines[i], sizeof(article.lines[i]), stdin);
article.lines[i][strcspn(article.lines[i], "\n")] = '\0'; // 去掉fgets读入的换行符 }
countCharsAndSpaces(article); printf("请输入要统计出现次数的字符串:");
fgets(substring, sizeof(substring), stdin); substring[strcspn(substring, "\n")] = '\0'; // 去掉fgets读入的换行符
int numOccurrences = countSubstringOccurrences(article, substring);
printf("字符串 \"%s\" 在文章中出现的次数:%d\n", substring, numOccurrences);
printf("删除字符串后的文章:\n");
removeSubstring(&article, substring);
}
return 0;
}