1

这是我在这里匹配子字符串的程序。我想改变程序中输入和输出的工作方式。

问题定义:

  • 提示用户输入多少个字符串 (N)
  • N 个字符串将在单独的行中输入
  • 对于每个字符串,
  • 如果它以“hackerrank”开头,则打印 1
  • 如果以“hackerrank”结尾,则打印 2
  • 如果它以“hackerrank”开头和结尾,则打印 0
  • 如果以上都不是,则打印 -1

例子:

输入:

4
i love hackerrank
hackerrank is an awesome place for programmers
hackerrank
i think hackerrank is a great place to hangout



Output:
2
1
0
-1

这是我的实际代码。

int main()
{

    vector<string> token_store;
    string s,token;



    getline(cin,s);
    std::istringstream iss(s);


    while(iss>>token)
        token_store.push_back(token);   //splitting strings into tokens


    int len=token_store.size();        //storing size of vector

    if(token_store[0]=="hack" && token_store[len-1]=="hack")
       cout<<"first and last same";     //if first and last word of input string is hack
    else if(token_store[0]=="hack")
       cout<<"first matches";                                    //if first word of input string is hack
    else if(token_store[len-1]=="hack")
       cout<<"last matches";                                 //if last word of input string is hack

}
4

1 回答 1

2

以下代码将读取输入并检查字符串“hackerrank”

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> token_store;
    int amount;
    string s;

    cin >> amount;
    cin.ignore();

    for(int i = 0; i < amount; i++){
        getline(cin, s);
    token_store.push_back(s);
    }

    string match = "hackerrank";

for(int i = 0; i < amount; i++){
    bool starts = false;
    bool ends = false;
    string str = token_store[i];

    if(str.length() < match.length()){
        std::cout << -1 << "\n";
        continue;
    }
    starts = str.substr(0, match.length()) == match; // Check if string starts with match
    ends = str.substr(str.length()-match.length()) == match; // Check if string ends with match

    if(starts && ends)
        std::cout << 0 << "\n";
    else if(starts)
        std::cout << 1 << "\n";
    else if(ends)
        std::cout << 2 << "\n";
    else
        std::cout << -1 << "\n";

    }
    return 0;
}
于 2013-10-16T16:39:17.460 回答