我正在嘗試創建貫穿單詞的邏輯,并嘗試查找是否存在多次使用的字母。如果一個字母重復,則將其更改為“1”,如果不是則將其更改為“2”。示例:雷達 - 11211,亞馬遜 - 121222,空手道 - 212122。具體問題是,如果我使用 for(),每個字母都與最后一個進行比較。另外我不明白如何使用 for() 檢查最后一個字母。最后一個字母總是 2。
這是我的代碼:
#include <iostream>
#include <string>
using namespace std;
int main()
{ string word;
char bracket1('1');
char bracket2('2');
cout << "Write your word: ";
cin >> word;
for (int i = 0; i < word.length(); i)
{
char let1 = word[i];
char let2 = word[i 1];
if (let1 == let2)
{ word[i] = bracket1;}
else
{ word[i] = bracket2; }
} cout << word;
}
示例:測驗回傳 1e22 而不是 1221
uj5u.com熱心網友回復:
在回圈中寫入時,您的程式中有未定義的行為。這是因為你要為邊界的最后一個值的出使用。word[i 1];forii 1
解決此問題的一種可能方法是使用std::map如下所示的方法。在給定的程式std::tolower中使用是因為您希望大寫和小寫字母被相同對待。
#include <iostream>
#include <map>
#include <algorithm>
int main()
{
std::string word;
std::cout << "Write your word: ";
std::getline(std::cin, word);
//print out the word before replacing with 1 and 2
std::cout<<"Before transformation: "<<word<<std::endl;
std::map<char, int> charCount; //this map will keep count of the repeating characters
//iterate through each character in the input word and populate the map
for(char &c: word)
{
charCount[std::tolower(c)] ;//increment the value by 1
}
//replace the repeating characters by 1 and non-repeating by 2
for(char &c: word)
{
if(charCount.at(std::tolower(c)) > 1)
{
c = '1';
}
else
{
c = '2';
}
}
//print out the word after transformation
std::cout<<"After transformation: "<<word<<std::endl;
return 0;
}
程式的輸出可以在這里看到。
輸入的輸出Amazon是:
Write your word: Amazon
Before transformation: Amazon
After transformation: 121222
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373408.html
上一篇:如何在javascript中將變數(數值)轉換為另一個值(如像素值)?[復制]
下一篇:誰能解釋一下這是如何作業的?
