用C语言编写函数计算子字符串substr在主字符串mainstr中的索引值
来源:互联网 发布:ubuntu中国官网 编辑:程序博客网 时间:2024/06/09 17:52
在大小写敏感的前提下,用C语言编写函数计算子字符串substr在主字符串mainstr中的索引值。
如果substr完全包含在mainstr中,请计算出索引值。否则,返回-1.
具体代码如下:
findstr.c
/**Author: snowdream <yanghui1986527@gmail.com>Data: 2012.03.05Description:假设一个主要字符串“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 -gsnowdream@snowdream:~$ ./findstr The index of cctv in Hello World! is: -1The index of World in Hello World! is: 6
- 用C语言编写函数计算子字符串substr在主字符串mainstr中的索引值
- 用c语言实现 编写一个函数,它从一个字符串中提取一个子字符串
- C语言编写 删除字符串中的子串
- 【c语言】编写一个函数计算字符串长度
- 用C语言编写函数,实现strlen计算字符串长度的功能
- C语言 编写一个函数,它从一个字符串中提取一个子字符串
- C语言 编写一个函数,它从一个字符串中提取一个子字符串。
- 【c语言】编写一个函数,它从一个字符串中提取一个子字符串
- C语言:编写从一个字符串中提取一个子字符串的函数my_substr
- getIndexesInTextarea(计算字符串在TextArea中的索引)
- 下面的函数统计子字符串substr在字符串str中出现的次数,如果substr在str中不出现,则返回值0
- C语言中的字符串函数
- C语言中的字符串函数
- 在C语言中的字符串
- 【C语言】编写函数实现字符串旋转
- 编写常见C语言字符串函数
- c语言替换字符串中的子串
- 统计字符串的某一子串在字符串中的出现次数(C语言实现)
- 关于类程序改错
- 关于Linux直接写屏资料
- C语言学习之路之二-----------C语言中的常量与变量
- 第十六周实验报告(任务一)
- openocd zylin
- 用C语言编写函数计算子字符串substr在主字符串mainstr中的索引值
- MFC定时器的应用
- ajax案例-ajax+js+dom+json+php+mysql仿google分页1
- 用sqlplus远程连接oracle命令
- 第十六周实验报告(任务二)
- 编程题--625的平方等于390625--还有其它的3位数有这个特征吗?试编程求出。
- javascript游戏引擎
- Java web应用中的常见字符编码问题的解决方法
- 清华大学2000年复试上机题 解题报告