现在的位置: 首页 > 综合 > 正文

用C语言编写函数计算子字符串substr在主字符串mainstr中的索引值

2013年09月03日 ⁄ 综合 ⁄ 共 966字 ⁄ 字号 评论关闭

在大小写敏感的前提下,用C语言编写函数计算子字符串substr在主字符串mainstr中的索引值。

如果substr完全包含在mainstr中,请计算出索引值。否则,返回-1.

具体代码如下:

findstr.c

/**

Author: snowdream <yanghui1986527@gmail.com>

Data: 2012.03.05

Description:
假设一个主要字符串“Hello World!”,和一个子字符串"World".
在大小写敏感的前提下,如果主字符串包含子字符串,请写出一个函数
计算出该子字符串在主字符串中的索引index。否则返回 -1 作为索引值。

*/




#include <stdio.h>

int findstr(char* substr,char* mainstr)
{
    int index = -1;
    
    for(int i = 0; *(mainstr+i)!='\0';i++)
    {
        for(int j = 0; *(substr+j)!='\0';j++)
        {
            if(*(substr+j) != *(mainstr+i+j))
                break;
            
            if(*(substr+j+1) =='\0' )
                index = i;
        }
        
       if(index != -1)
           break;
    }    
    
    return index;
}


int main()
{
    int index = -1; 
    int index1 = -1;
    
    char* mainstr = "Hello World!";
    char* substr = "cctv";  
    char* substr1 = "World";
   
    index = findstr(substr,mainstr);
    index1 = findstr(substr1,mainstr);
   
    printf("The index of %s in %s is: %d\n",substr,mainstr,index);
    printf("The index of %s in %s is: %d\n",substr1,mainstr,index1);

    return 0;
}

在ubuntu下编译运行:

snowdream@snowdream:~$ gcc findstr.c -std=gnu99 -o findstr -g
snowdream@snowdream:~$ ./findstr 
The index of cctv in Hello World! is: -1
The index of World in Hello World! is: 6

抱歉!评论已关闭.