zoukankan      html  css  js  c++  java
  • 《c程序设计语言》读书笔记-4.1-判断字符串在另一个字符串中的位置

    #include <io.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <math.h>
    #include <time.h>
    
    #define Num 20
    
    int strindex(char s[],char t[])
    {
        int i,j,k;
        int position = -1;
    
        for(i = 0;s[i] != '';i++)
        {
            for(j = i,k = 0;t[k] != '' && s[j] == t[k];j++,k++)
                ;
            if(k > 0 && t[k] == '')
                position = i;
        }
        return position;
    }
    
    int main()
    {
        char str1[20],str2[20];
        char c;
        int i = 0,j = 0;
        int position;
    
        printf("please input string1
    ");
        while((c = getchar()) != '
    ' && i < Num)
        {
            str1[i++] = c;
        }
        str1[i] = '';
    
        printf("please input string2
    ");
    
        while((c = getchar()) != '
    ' && j < Num)
        {
            str2[j++] = c;
        }
        str2[j] = '';
        position = strindex(str1,str2);
    
        printf("%d
    ",position);
    
    	return 0;
    }
    
    

    上面的程序是正确的,可以正常运行得出结果,不过,我又编了下面的函数:

    #include <io.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <math.h>
    #include <time.h>
    
    
    
    int strindex(char s[],char t[])
    {
        int i,j,k;
        int position = -1;
    printf("%d
    ",strlen(s));
        for(i = 0;i < strlen(s);i++)
        {
        printf("%d
    ",i);
            for(j = i,k = 0;k < strlen(t) && s[j] == t[k];j++,k++)
                ;
            if(k > 0 && t[k] == '')
                position = i;
        }
        return position;
    }
    
    int main()
    {
        char *str1,*str2;
        int i = 0,j = 0;
        int position;
    
        printf("please input string1
    ");
        gets(str1);
    
        printf("please input string2
    ");
        gets(str2);
    
        position = strindex(str1,str2);
    
        printf("%d
    ",position);
    
    	return 0;
    }
    
    


    为了不定义数组的大小就用的指针,可是程序错了。。gets函数只能读入8个字符,这里面有问题,可是我不知道哪里错了,待看完指针那章看能不能解决!

  • 相关阅读:
    常用 Git 命令清单
    radhat 6.4/centos 6.4 下编译安装 最新ruby 2.1.5
    centos 6.4/redhat 6.4 安装gitlab
    微信小程序——navigator无法跳转
    微信小程序——修改data里面数组某一个值
    微信小程序——template的循环嵌套
    微信小程序——template的使用方法
    node学习笔记8——发布npm包
    淘宝镜像使用方法
    node学习笔记7——npm安装包
  • 原文地址:https://www.cnblogs.com/batteryhp/p/5020459.html
Copyright © 2011-2022 走看看