期末复习GGG-----查找子串

郭的

char *search( char *s, char *t ){
	int i=0;
	while(s[i]){
		int j=0;
		if(s[i]==t[0]){
			while(s[i+j]==t[j]&&t[j]){
				j++;
			}
			if(t[j]=='\0')
			return s+i;
		}
		i++;
	}
	return NULL;
}

 AI的

#include <stdio.h>
#include <string.h>
#define MAXS 30

char *search(char *s, char *t);

int main()
{
    char s[MAXS], t[MAXS], *pos;

    fgets(s, sizeof(s), stdin);
    fgets(t, sizeof(t), stdin);
    // 去掉字符串末尾的换行符
    s[strcspn(s, "\n")] = '\0';
    t[strcspn(t, "\n")] = '\0';

    pos = search(s, t);
    if (pos != NULL)
        printf("%d\n", pos - s);
    else
        printf("-1\n");

    return 0;
}

// 修复并返回子串的位置
char *search(char *s, char *t)
{
    int len_s = strlen(s), len_t = strlen(t);
    for(int i = 0; i <= len_s-len_t; ++i){
        if(strncmp(s + i, t, len_t) == 0){
            return s + i;
        }
    }
    return NULL;
}

strncmp 和 strcmp

 

 

不包含<string.h>时如何计算字符串长度?

如果不允许使用标准库中的strlen()或其他函数来获取字符串长度,你可以通过循环遍历字符串直到遇到终止符\0的方式来手动计算长度。

int len = 0;
for (; s[len] != '\0'; len++); // 增量len直到遇到'\0'
char *search( char *s, char *t ) {
    int lens = 0; int lent = 0;
    int m, n;

    // 计算s和t的长度
    for(m = 0; s[m] != '\0'; m++) { lens++; }
    for(n = 0; t[n] != '\0'; n++) { lent++; }

    // 搜索过程
    for(int i = 0; i <= lens-lent; i++) {
        if(strncmp(s + i, t, lent) == 0) {
            return s + i;
        }
    }
    return NULL;
}

//从s串开始,第 i个元素之后的指针

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值