文章目录
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代表单词开始,