一、查找子串在母串中的位置
#include<iostream>
using namespace std;
int SearchIndex(char* str1, char* str2) //返回子串起始位在主串中的下标
{
int i, j;
for(i=0; i<sizeof(str1); i++)
{
if(str1[i]==str2[0]) //遍历到的字符与str2的首字符对应上了
for(j=1; j<sizeof(str2); j++) //就开始扫描str2剩下的字符是否都能与str1中的某段对应上
{
if(str1[i+j]==str2[j])
if(str2[j]!='\0')
return(i); //若str2被遍历完,说明都对应上了,返回此时主串的下标
else
break; //只要有一个不对应,就跳出遍历str2
}
}
}
int main()
{
char str1[10]= "abcdefg"; //主串
char str2[10]= "gh"; //子串
int res= SearchIndex(str1, str2); //返回的下标,或者出错码
if(res==8)
cout << str2 << "子串不存在于" << str1 << "主串中!";
else
cout << str2 << "子串在" << str1 << "主串的【" << res << "】位置上!";
}
二、一个实现字符串拼接的函数
#include<iostream>
#include<string.h>
using namespace std;
char* Strcat(char* str1, const char* str2) {
int n = strlen(str1);
int i = 0;
//字符串str1的地址和str2的地址同时后移,依次进行赋值,直到str2为空退出
while(str1++[i + n] = str2++[i]) ;
return str1;
}
int main()
{
char str1[10] = "abcd";
char str2[10] = "efghi123";
Strcat(str1, str2);
cout << "连接后的字符串为:" << str1;
}