最近参加的多次面试都考到了关于字符串查找的问题,下面就这些问题做一个简单的总结,前面的博文也提到不少关于字符串指针和字符串数组的差别等问题。
- 查找对应字符/字符串出现的次数
使用头函数string.h中包含的strstr函数,进行字符串查找
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char a[100] = {'\0'}, b[100] = {'\0'};
char *temp = '\0';
int count = 0;
printf("please input source string\n");
gets(a);
printf("please input find string\n");
gets(b);
temp = a; //将输入值赋值给temp指针,这样可以方便的进行数组操作
while(temp)
{
temp = strstr(temp, b); //strstr函数用于找出str2字符串
//在str1字符串中第一次出现的位置,未找到则返回NULL,包含文件string.h
if(temp) //如果temp不为NULL,则说明找到
{
temp += strlen(b);//向前加b字长位数,继续查找
count ++;
}
}
printf("find %d times\n", count);//返回查找到的值
system("pause");
return 0;
}
不使用库函数直接查找
long GetCount(char *sStr,char *dStr)
{
if(sStr==NULL||dStr==NULL) return 0;
char *p=sStr;
long count=0;
while(*p)
{
char *s=p;
char *d=dStr;
bool matching;
matching = true;
while(*d)
{
if(*s=='\0')
return count;
if((*s!=*d))
{
matching = false;
break;
}
s++;
d++;
}
if(matching) count++;
p++;
}
printf("%ld\n", count);
return count;
}
int main()
{
char sStr[100]; //= "countryCodeISO2countryCodeISO2countryCodeISO2countryCodeISO2countryCodeISO2countryCodeISO";
char dStr[100]; // = "country";
long num = 0;
gets(sStr);
gets(dStr);
num = GetCount(sStr, dStr);
printf("%ld\n", num);
system("pause");
return 0;
}2、查找重复字符/字符串,重复频次
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
char get_onlyone(char* str)
{
int i;
int hash[128];
int len = strlen(str);
memset(hash, 0, sizeof(hash));
for(i = 0; i < len; i++) {
hash[str[i]-'0']++;
}
for(i = 0; i < len; i++) {
if(hash[str[i]-'0'] == 1) return i;
}
return 0;
}
int main(void)
{
char str[128] = {'\0'};
gets(str);
//while(scanf("%s", str) != EOF) {
printf("返回第%d个字符,字符为%c \n", get_onlyone(str) + 1, str[get_onlyone(str)]);
//}
system("pause");
return 0;
}
1186

被折叠的 条评论
为什么被折叠?



