用C++编写一个程序

来源:百度知道 编辑:UC知道 时间:2024/06/08 11:56:53
用C++编写一个程序,用于接受两个字符串,判断第一个字符串中是否包含第二个字符串,如果包含说明第二个字符串在第一个字符串中的位置(即,第二个字符串在第一个字符串中出现的位置)。
编不好,希望高人指点!谢谢!

主要的算法

int Index(STRING s1,STRING s2)
{
len1=Length(s1); len2=Length(s2); //计算s1和s2的长度
i=0; j=0; //设置两个扫描指针
while (i<len1&&j<len2) {
if (s1.str[i]==s2.str[j]) { i++; j++; }
else {i=i-j+1; j=0;} //对应字符不相等时,重新比较
}
if (j==len2) return i-len2+1;
else return 0;
}

string str1( "Alpha Beta Gamma Delta" );
string::size_type loc = str1.find( "Omega", 0 );
if( loc != string::npos )
cout << "Found Omega at " << loc << endl;
else
cout << "Didn't find Omega" << endl;

http://www.cppreference.com/cppstring/find.html

呵呵!
其实这个很简单哦!主要用到的是两个字符串的匹配算法哦!
不过楼主要谨记:程序要靠自己写哦

呵呵!完整的C++算法如下
#include <iostream.h>
#define