작성하려고하는 재귀 함수에 문제가 있습니다. 이 함수의 목적은 문자열 내에서 문자열을 찾은 다음 두 번째 문자열이 첫 번째 재귀를 사용하는 색인 안에있는 인덱스를 반환하는 것입니다.문자열 재귀 함수 오류 내의 문자열
나는 이것을 할 수있다. 두 번째 문자열이 첫 번째 문자열에 포함되지 않은 경우 문제가 발생합니다. 두 번째 문자열을 찾지 못했음을 사용자에게 알려야합니다. 그 메시지를 전달할 수는 없습니다.
int index_of(string s, string t){
int len1 = s.length(), len2 = t.length(), index = 0;
if (len1==len2){
if (s.substr(index, len2) == t){
return index;
}else{
return -1;
}
else{
index++;
return index_of(s.substr(index, len1),t)+index;
}
}
int main(){
string strOne = "", strTwo = "";
cout << "This program will find the ocurrence of one string within another.\n\nEnter the string to be searched:\t";
getline(cin, strOne);
cout << "\nNow enter the string you want to search for:\t";
getline(cin, strTwo);
int index = index_of(strOne, strTwo);
if (index == -1){
cout << "\nThe second string cannot be found. Sorry!\n\n";}
else{
cout << "\nThe index of the substring is:\t" << index << "\n\n";
}
system("PAUSE");
return 0;
}
모든 도움을 주시면 감사하겠습니다. :)
그런 목적으로 재귀 함수를 사용하면 안됩니다. 큰 문자열에서는 스택 오버플로가 발생합니다. – Heavy
저는 C++ 프로그래머가 아니지만 다음과 같이 문자열을 비교할 수 있습니까 : 'str1 == str2'? strcmp (str1, str2)를 사용할 필요가 없습니까? 첫 번째 옵션은 문자열의 주소 만 비교한다고 생각하십니까? – linluk
가능한 복제본 [재귀 적으로 벡터를 비교하는 방법] (http://stackoverflow.com/questions/26353067/how-to-recursively-compare-vectors) – smac89