再次运行程序并将结果存储在数组中

时间:2013-10-16 15:56:02

标签: c++

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

问题定义:

  • 系统会提示用户输入的字符串数量(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

}

1 个答案:

答案 0 :(得分: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;
}