题目
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
写一个函数,如果传入的第一个参数(字符串)以第二个参数(也是一个字符串)结尾,则它返回 true。
例子:
代码语言:javascript复制solution('abc', 'bc') // returns true
solution('abc', 'd') // returns false
代码区:
代码语言:javascript复制#include <stdbool.h>
bool solution(const char *string, const char *ending)
{
return true;
}
代码语言:javascript复制#include <string>
bool solution(std::string const &str, std::string const &ending) {
return true;
}
解答
CPP
代码语言:javascript复制#include <string>
bool solution(const std::string& str, const std::string& ending) {
return str.size() >= ending.size() && str.compare(str.size() - ending.size(), std::string::npos, ending) == 0;
}
代码语言:javascript复制bool solution(std::string const &str, std::string const &ending) {
return (std::string(str.end() - ending.size(), str.end()) == ending);
}
代码语言:javascript复制bool solution(std::string const &str, std::string const &ending) {
const int slen = str.length();
const int eLen = ending.length();
if (slen < eLen) {
return false;
}
for (int i = 1; i <= eLen; i ) {
if (str[slen - i] != ending[eLen - i]) {
return false;
}
}
return true;
}
C
代码语言:javascript复制#include <stdbool.h>
#include <string.h>
bool solution(const char *string, const char *ending)
{
int len = strlen(string) - strlen(ending);
return len < 0 ?false :strcmp(string len, ending) == 0;
}
代码语言:javascript复制#include <stdbool.h>
#include <string.h>
bool solution(const char *string, const char *ending)
{
int slen = strlen(string);
int elen = strlen(ending);
if (slen < elen) return false;
int y = 0;
for(int x = slen - elen; x <= slen; x)
{
if(string[x] != ending[y])
{
return false;
}
y;
}
return true;
}
代码语言:javascript复制#include <stdbool.h>
bool solution(const char *string, const char *ending) {
int str1 = strlen(string);
int str2 = strlen(ending);
return str1 >= str2 ? 0 == memcmp(&string[str1 - str2], ending, str2) : false;
}
D
代码语言:javascript复制#include<iostream>
using namespace std;
bool solution(string const& str, string const& ending) {
int n1 = strlen(str.c_str());//获取字符串长度
int n2 = strlen(ending.c_str());
int flag = 0;
for (int i = n1 - n2 ; i < n1; i )
{
if (str[i] == ending[flag]) flag ;
else return false;
}
if (flag = n2)return true;
}
int main()
{
string str , ending;
cin >> str; cin >> ending;
cout<<solution(str, ending);
system("pause");
return 0;
}
PS
strlen()函数
strlen()
函数 用于 计算 指定字符串的 长度,但 不包括 结束字符(打印字符串长度)。
注意事项:
代码语言:javascript复制#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[] = "abc";
// "abc" -- 'a' 'b' 'c' '