C++ 实现beginwith()和endwith()

#include<iostream>
#include<string>
using namespace std;
int endswith(string s, string sub) {
	if (s.rfind(sub) == -1) {//排除出现类似s:23   sub:123的情况.
		return 0;
	}
	else {
		return s.rfind(sub) == (s.length() - sub.length()) ? 1 : 0;
	}

}
int startswith(string s, string sub) {
	
		return s.find(sub) == 0 ? 1 : 0;
}
int main()
{	
	string str = "Helloworld";
	string str1 = "He";
	string str2 = "ld";
	if (startswith(str, str1)) {
		cout << str << " startwith " << str1 << endl;
	}
	if (endswith(str, str2)) {
		cout << str << " endwith " << str2 << endl;
	}
	return 0;
}

 

你可能感兴趣的