用C語言編寫函數計算子字符串substr在主字符串mainstr中的索引值
在大小寫敏感的前提下,用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
最後更新:2017-04-02 22:16:31