编写c语言遇到问题,子串不会

运用c语言编程:在main函数中创建一个文件,将键盘输入的字符串写入到文件中。打开该文件,读出字符串。将字符串中的大写字母变为小写字母,删除指定的子串,并输入子串出现的次数,串中剩余的字符形成的新串存放到另一个文件中,要求:子串由键盘输入,不区分大小写。

https://blog.csdn.net/u011910350/article/details/53024314 子串查询可供参考。

建议参考。

https://zhidao.baidu.com/question/568158001.html

#include<stdio.h>  
int main() 
{  
    int i;
    char a[100];
    gets(a);
    for(int i=0;a[i]!='\0';i++)   
          if(a[i]>='A'&&a[i]<='Z')  
              a[i]+=32; 
      puts(a);  
    return 0;
}
/*
输出: 
adsFSDFsadDFHF
adsfsdfsaddfhf
*/

 

代码如下,如有帮助,请采纳一下,谢谢。

#include <stdio.h>
#include <string>
//在p中查找sub
int findstr(char* p,char* sub)
{
	int len = strlen(p);
	int lensub = strlen(sub);
	for (int i = 0; i  <= len - lensub; i++)
	{
		bool b = true;
		for (int j = 0; j < lensub; j++)
		{
			if (p[i+j] != sub[j])
			{
				b = false;
				break;
			}
		}
		if(b)
			return i;
	}
	return -1;
}


int main()
{ 
	char buf[1024] = {0};
	FILE* fp;
	printf("请输入字符串:\n");
	gets(buf);	
	if ( !(fp = fopen("a.txt","w+")) )
	{
		printf("a.txt 打开失败\n");
		return 0;
	}
	//写入文件
	fwrite(buf,1,strlen(buf),fp);
	fclose(fp);
	fp = 0;

	memset(buf,0,1024);
	printf("请输入要删除的字串:");
	gets(buf);

	//读文件
	if ( !(fp = fopen("a.txt","r+")))
	{
		printf("a.txt打开失败\n");
		return 0;
	}
	//读取文件内容
	fseek(fp,0,SEEK_END);
	long lSize = ftell(fp);
	char* text=new char[lSize+1];
	rewind(fp); 
	lSize = fread(text,sizeof(char),lSize,fp);
	text[lSize] = '\0';
	fclose(fp);
	fp = 0;

	//将大写字母转成小写
	for (int t = 0; t < lSize; t++)
	{
		if (text[t] >= 'A' && text[t] <= 'Z')
		{
			text[t] += 32;
		}
	}
	for(int t = 0; t < strlen(buf);t++)
	{
		if (buf[t] >= 'A' && buf[t] <= 'Z')
		{
			buf[t] += 32;
		}
	}

	//删除字串
	int nmb = 0;
	char* tmp = new char[lSize + 1];
	int start = 0;
	int end = 0;
	int shift = 0;  //tmp中的偏移量
	while(true)
	{
		end = findstr(text+start,buf);
		if (end == -1)
		{
			end = lSize;
			memcpy(tmp+shift,text+start,end - start);
			shift += (end - start);
			break;
		}else
		{
			end = end + start;
			memcpy(tmp+shift,text+start,end - start);//abce111abcabc
			shift += (end - start);
			start = end + strlen(buf);
			nmb++;
		}
	}
	tmp[shift] = '\0';
	printf("字符出现次数:%d,删除后的字符:%s\n",nmb,tmp);
	//打开文件写入
	if (!(fp = fopen("b.txt","w+")))
	{
		printf("b.txt打开失败\n");
		return 0;
	}
	fwrite(tmp,1,shift,fp);
	fclose(fp);

	delete[] tmp;
	tmp = 0;
	delete[] text;
	text = 0;

	//getchar();
	//getchar();
	return 0;
}

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632