ポインタについて理解を深めるために演習問題をやるよ

問題4

bool isIncluded(char str1[], char str2[]); 与えられた文字列str1の中にstr2が含まれていたら、true含まれていなかったらfalse を返す関数を作りなさい。
問題の前提として、 str1の長さ >= str2の長さ とします。

例1) str1: “yamadatarou” str2: “mad” 結果:true

例2) str1: “yamadatarou” str2: “max” 結果:false

解答

これも、いろいろやり方は考えられると思います
問題3の'@'を探した方法を使って、str2[]の1文字目を見つけたら、2文字目、3文字目。。。がstr1[]と同じか確認する方法、
が一番単純な気がします。

解答例 素朴な方法

この方法は素朴で、かつ、様々な応用(力業でいろいろな問題を解決できる)手法なので、理解しておくと強くなれます。

まず、main関数でこんな感じに使うんだろうなっていうところを見ていきます。
下のソースコードのように呼んでみて、結果が以下の様になればOKそうです。

main.cpp
int main() {
	char s1[] = "yamadatarou";//この中にmadがないか探索する文字列
	char s2[] = "mad";//探索文字列
	char s3[] = "okazakitarou";//全然一致しない文字列
	char s4[] = "mamamamap";//一致しそうでしない
	char s5[] = "yamamamdmad";//最後の最後に一致
 
 
	std::cout << std::boolalpha << isIncluded(s1, s2) << std::endl;
	std::cout << std::boolalpha << isIncluded(s3, s2) << std::endl;
	std::cout << std::boolalpha << isIncluded(s4, s2) << std::endl;
	std::cout << std::boolalpha << isIncluded(s5, s2) << std::endl;
}

実行結果の表示

true
false
false
true

そんで、関数のソースコードを示します。
一応ちゃんとみんな分割コンパイル習ったので、.hと.cppに分けてみました。

isIncluded.h
bool isIncluded(char str1[], char str2[]);
isIncluded.cpp
#include "isIncluded.h"
 
 
bool isIncluded(char str1[], char str2[])
{
	char *pStr1, *pStr2;
	pStr2=str2;
	for(char *pStr1=str1;*pStr1!='\0';pStr1++)
	{
		if(*pStr2 == *pStr1)
		{
			//ループに戻った時にpStr1がずれてると困るからコピーして使う
			char *t_str1 = pStr1;
			char *t_str2 = pStr2;
			//文字列が一致してるかどうか1文字ずつ確認していくループ
			while(true)
			{
				++t_str1; //1文字先を見る
				++t_str2; //1文字先を見る
				if(*t_str2 == '\0')
					return(true);
				//Str1の方が先に'\0'にたどり着いていない、かつ
				//Str1とStr2の文字が一緒なら、探索を続ける
				//それ以外の時は、もう一致してないからbreak!
				if(*t_str1 == *t_str2 && *t_str1 !='\0')
					continue;
				else
					break;
			}
		}
	}
	return(false);
}

ちなみに、stringクラスを使うと、数行で終わってしまいます。。。
stringクラスのfindメンバー関数で、部分文字列の検索ができます。
見つかった場合は、初めに出現した位置を、見つからない場合には、見つからないことを示すメンバ変数strind::nposを返します。
なので、nposが返ってきてなかったらtrue、nposが帰ってきたらfalseを返せば、良い。。。だけ。
努力とは。。。って感じになるね。はぁ。

main.cpp
#include <iostream>
#include <string>
 
using std::cout;
using std::cin;
using std::endl;
using std::string;
 
bool isIncluded(string _s1, string _s2)
{
	if(_s1.find(_s2) != string::npos)
		return(true);
	else
		return(false);
}
 
 
int main() {
	string s1 = "yamadatarou";//この中にmadがないか探索する文字列
	string s2 = "mad";//探索文字列
	string s3 = "okazakitarou";//全然一致しない文字列
	string s4 = "mamamamap";//一致しそうでしない
	string s5 = "yamamamdmad";//最後の最後に一致
 
	cout << std::boolalpha << isIncluded(s1, s2) << endl;
	cout << std::boolalpha << isIncluded(s3, s2) << endl;
	cout << std::boolalpha << isIncluded(s4, s2) << endl;
	cout << std::boolalpha << isIncluded(s5, s2) << endl;
}

戻る