編程題:有兩個字符串str1和str2,寫一個函數實現在str1中查找str2的初始位置,要求不區分大小寫

編程題:有兩個字符串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;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章