这是我的程序,用于匹配子字符串。我想改变输入和输出在我的程序中的工作方式。
输入:
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
}
答案 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;
}