[英]If a word is repeated many times in a string, how can I count the number of repetitions of the word and their positions?
[英]How to find positions of repeated characters in a string?
如何找到字符串中重复字符的位置? 例如,输入的字符串是“11-28-1995”。 我的目标是在“-”(一个变量)之间分配这些值中的每一个,这样我就会得到月 = 11、日 - 28 和年 = 1995。这就是我到目前为止所得到的,尽管我不确定如何在一个月后迭代。
#include <iostream>
using namespace std;
int main() {
string input;
cout << "What is the date?" << endl;
cin >> input;
int pos = input.find("-");
int month = stoi(input.substr(0, pos));
cout << month << endl;
cout << day << endl;
return 0;
}
也许您正在寻找这样的东西:
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include <sstream>
#include <cassert>
using namespace std;
int main() {
string input;
cout << "What is the date?" << endl;
cin >> input;
unsigned int day = 0;
unsigned int month = 0;
unsigned int year = 0;
stringstream ostr(input.c_str());
char c1, c2 = 0;
ostr >> day >> c1 >> month >> c2 >> year;
assert((c1 == c2) && (c2 == '/'));
cout << "Day: " << day << endl;
cout << "Month: " << month << endl;
cout << "Year: " << year << endl;
return 0;
}
对于更通用的令牌提取器,您可能对 getline 的使用感兴趣:
希望能帮助到你;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.