面试题——关于字符串查找

3 篇文章 0 订阅

最近参加的多次面试都考到了关于字符串查找的问题,下面就这些问题做一个简单的总结,前面的博文也提到不少关于字符串指针和字符串数组的差别等问题。

  1. 查找对应字符/字符串出现的次数

             使用头函数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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值