给定string str1和string str2,编写一个库函数,返回str2在str1中的位置。
如:str1为"ABCDLANCEXYZ",str2为"LANCE",则返回位置5。如果没有找到,返回-1。(起始位置从1开始)
// findSubStrPosition.c
#include <stdio.h>
int findSubStrPosition(const char *pStr1, const char *pStr2)
{
int len1 = strlen(pStr1);
int len2 = strlen(pStr2);
if (len1 < len2)
return -1;
int i = 0;
for ( ; i < len1; i++)
{
int j = 0;
if (pStr1[i] != pStr2[j])
continue;
while(j < len2 & i+j < len1)
{
j++;
if (pStr1[i+j] != pStr2[j])
break;
}
if (j == len2)
return i+1 ; // start 1
}
return -1;
}
int main()
{
const char *str1 = "ABCDLANCEXYZ";
const char *str2 = "LANCE";
int position = 0;
position = findSubStrPosition(str1, str2);
printf("the substring position is %d\n", position);
return 0;
}
// findSubStrPosition.cpp
#include <iostream>
#include <string>
bool isSubstr(std::string str1, std::string str2)
{
if (str1.length() < str2.length())
return false;
int index = 0;
while(index < str2.length())
{
if(str2[index] == str1[index])
index++;
else
return false;
}
return true;
}
int findSubStrPosition(std::string str1, std::string str2)
{
int index = 0;
while(index < (str1.length() - str2.length()))
{
if (isSubstr(str1.substr(index), str2))
return index + 1; // start 1
else
index++;
}
return -1;
}
int main()
{
std::string str1 = "ABCDLANCEXYZ";
std::string str2 = "LANCE";
int position = 0;
position = findSubStrPosition(str1, str2);
std::cout<< "the substring position is "<< position << std::endl;
//std::cout<< "the substring position is "<< str1.find(str2) << std::endl;
return 0;
}