![](/img/trans.png)
[英]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.