编程题:有两个字符串str1和str2,写一个函数实现在str1中查找str2的初始位置,要求不区分大小写
思路:1:首先判断两个字符串的大小,作初步比较
2:构建str1字符串的for循环,在此循环里实现str2字符串的for循环,从str1字符串首字符开始循环查找str2中的 首字符,如首字符都相等,则两个字符索引顺次递增,看下一字符是否相同。若有不同,str1字符递增到下 下一位,str2返回到初始字符再次判断。
3:注意不区分大小写的操作
/************************************************************************/
/* 题目:有两个字符串str1和str2,写一个函数实现在str1中 */
/* 查找str2的初始位置,要求不区分大小写 */
/************************************************************************/
C语言版
#include <stdio.h>
#include <string.h>
//若str2不在str1中,返回-1
int SearchStrPosition(char* str1, char* str2)
{
int len1,len2;
int position = -1;
len1 = strlen(str1);
len2 = strlen(str2);
if(len2 > len1) //若str2的长度大于str1,则str2必不可能在str1中,直接输出-1
{
return -1;
}
int i;
int j;
for(i = 0; i < len1; i++)
{
for(j = 0; j < len2; j++)
{
if(i + j >= len1) //i循环到末端还没找到,导致剩下的字符串数目比str2长度短,肯定不会再有
return -1;
if(str1[i + j] != str2[j] && str1[i + j] != str2[j] + 32 && str1[i + j] != str2[j] - 32)
{
break;
}
if(j == len2 - 1) //j索引到len2的最后,表明前面字符都符合,记录下此时str1的索引位置即为想要的结果
position = i;
}
}
return position;
}
int main()
{
char s1[4096], s2[4096];
char *str1 = s1, *str2 = s2;
int pos;
printf("please enter one chars for str1\n");
scanf("%s",str1);
printf("please enter one chars for str2\n");
scanf("%s",str2);
pos = SearchStrPosition(str1,str2);
if(pos != -1)
printf("the position of str2 in the str1 is %d",pos);
else
printf("The %s can not been included into %s",str2,str1);
return 0;
}
//C++版
#include <iostream>
#include <string>
using namespace std;
int SearchStrPosition(string str1,string str2)
{
int len1, len2;
int pos = -1;
//获取两字符串长度
len1 = str1.size();
len2 = str2.size();
//若str2的长度大于str1,则str2必不可能在str1中,直接输出-1
if(len2 > len1)
return -1;
//因为不区分大小写,将str1和str2全部转换为小写
for(int i =0; i < len1; i++)
str1[i] = tolower(str1[i]);
for(int i = 0; i < len2; i++)
str2[i] = tolower(str2[i]);
//循环判断str2是否在str1之中,若在,记录str2首字符在str1中的位置
for(int i = 0; i < len1; i++)
{
for(int j = 0; j < len2; j++)
{
if((i + j) >= len1)
return -1;
if(str1[i + j] != str2[j])
break;
if(j == len2 - 1)
pos = i;
}
}
return pos;
}
int main()
{
string str1,str2;
int pos;
cout<<"please enter chars for str1\n"<<endl;
cin>>str1;
cout<<"please enter chars for str2\n"<<endl;
cin>>str2;
pos = SearchStrPosition(str1,str2);
if(pos != -1)
cout<<"the position of str2 in the str1 is "<<pos<<endl;
else
cout<<"The "<<str2<<" can not been included into "<<str1<<endl;
return 0;
}