再次运行程序并将结果存储在数组中
Running program again and storing result in an array
这是我在这里用于匹配子字符串的程序。我想更改程序中输入和输出的工作方式。
问题定义:
- 系统会提示用户输入多少个字符串 (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
}
以下代码将读取输入并检查字符串"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;
}
相关文章:
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 使用 Xcode 将双精度存储在数组C++中
- 访问表示 2D 矩阵的 1D 存储数组
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 如何在队列中存储数组
- 按列主要顺序迭代行大量存储数组
- 如何使存储数组的二进制搜索稳定
- 将行中的字段从textfile中更改为存储数组,而不是重新编写文件
- 存储数组索引值C++
- 存储数组的地方,如果我在返回后声明它
- 缺少存储数组地址的内存
- 使用static在函数中存储数组各个组件的值
- 如何存储数组的每个相邻子数组的和
- 在c++中存储数组映射
- 存储数组的地址列表,以解析原始的非终止文本
- 用于存储数组的字符串
- c++存储数组下一个位置的地址
- 在 for 循环中创建和存储数组