C:与字符串相关的基础题目


1、母串中查子串出现次数

在这里插入图片描述

#include <stdio.h>
#include <string.h>
char str1[110], str2[30]; //1是母串
int main()
{
   
    int findCount(char *str1, char const *str2);//这里的str与定义的字符数组没关系,这里是两个指针,别看错了
    scanf("%s %s", str1, str2);
    printf("%d", findCount(str1, str2));
    //system("pause");
    return 0;
}
//查找次数
int findCount(char *str1, char const *str2)
{
   
    int count = 0;
    char *ptmp = str1;
    while ((ptmp = strstr(ptmp, str2)) != NULL) //strstr返回查重后子串首字符在母串中地址
    {
   
        ptmp += strlen(str2); //往后移动指针
        count++;
    }
    return count;
}

1、常量指针(先常量限制符号,在指针符号,const int*)
注:这种限制C++中用的特别多,目的就是传递地址,而不改变其值,相当于把引用类型值传递化!

特点:可以随时改变指针的地址,但是不能改变指向地址中的值!相当于一个地址变量

2、指针常量(先指针符号,在常量限制符号,int * const
特点:这个指针指向的地址已经固定不能再改变,相当于一个普通常量!

3、const限定符作用于函数参变量
注意:我们经常会看到很多函数的形参都会用const限定符修饰,那么为什么那么多形参都用const修饰呢?原因在于,我们传参数大都是会引用指针。而在这之前加上const是用以指明使用这种参数仅仅只是为了效率(因为传址比传值效率高),而不是想让调用函数修改对象的值(因为传址的不好的地方就是会把原始的址对应的值改变掉)。


2、字符串匹配

在这里插入图片描述
在这里插入图片描述
查颜色出现次数并输出出现最多次的颜色。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   
	int n, i, j, cnt[6];
	char color[6][10] = {
   "green", "red", "blue", "pink", "orange", "black"};
	char str[10];
	while (~scanf("%d", &n))
	{
   
		int ans = 0, max = 0;
		for (i = 0; i < 6; i++)
			cnt[i] = 0;
		for (j = 0; j < n; j++)
		{
   
			scanf("%s", str);
			for (i = 0; i < 6; i++)
				if (strcmp(color[i], str) == 0)//使用strcmp函数一个个比对
				{
   
					cnt[i]++;
					if (max < cnt[i])
					{
   
						max = cnt[i];
						ans = i;
					}
				}
		}
		printf("%s\n", color[ans]);
	}
	return 0;
}

3、分离句中单词

在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   
	char str[110];
	char ans[20][15];
	int i, pos1 = 0, pos2 = 0, sign = 1;
	while (gets(str) != NULL)
	{
   
		i = 0;//跳过句首空格
		if ((str[i] < 'a' || str[i] > 'z') && (str[i] < 'A' || str[i] > 'Z'))
			i++;
		pos1 = pos2 = 0;
		sign = 1;//sign=1代表单词开始,
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值