C++程式:獲取不同鍵盤佈局輸入的字串


假設我們有兩個字串S和T,以及另一個字串R。S和T代表兩種流行的鍵盤佈局,它們僅在字母位置上有所不同。所有其他鍵都是相同的。在S和T中,第一種和第二種佈局的所有鍵都是按相同順序排列的。R也可能包含數字。已知它是使用第一種佈局輸入的,但編寫者打算使用第二種佈局輸入。我們必須找到保持第二種佈局的字串。(由於兩種佈局中除了字母之外的所有鍵都是相同的,因此字母的大小寫應該保持不變,所有其他非字母字元也應該保持不變)。

問題類別

為了解決這個問題,我們需要操作字串。程式語言中的字串是儲存在特定陣列式資料型別中的字元流。幾種語言將字串指定為特定資料型別(例如Java、C++、Python);而其他幾種語言將字串指定為字元陣列(例如C)。字串在程式設計中非常重要,因為它們通常是各種應用程式中首選的資料型別,並用作輸入和輸出的資料型別。有各種字串操作,例如字串搜尋、子串生成、字串剝離操作、字串轉換操作、字串替換操作、字串反轉操作等等。檢視下面的連結,瞭解如何在C/C++中使用字串。

https://tutorialspoint.tw/cplusplus/cpp_strings.htm

https://tutorialspoint.tw/cprogramming/c_strings.htm

因此,如果我們問題的輸入類似於S = "qwertyuiopasdfghjklzxcvbnm"; T = "veamhjsgqocnrbfxdtwkylupzi"; R = "helloworld87nicecoding",則輸出將為"xawwqeqmwr87zglalqrgzf"

步驟

為了解決這個問題,我們將遵循以下步驟:

res := an empty string
for initialize i := 0, when R[i] is not equal to 0, update (increase i by 1), do:
   x := 0
   for initialize j := 0, when j < 26, update (increase j by 1), do:
      if R[i] is same as S[j], then:
         res := res + T[j]
         x := 1
         Come out from the loop
      otherwise when R[i] + 32 is same as S[j], then:
         k := T[j] - 32
         res := res + k
         x := 1
         Come out from the loop
   if x is same as 0, then:
      res := res + R[i]
return res

示例

讓我們來看下面的實現,以便更好地理解:

#include <bits/stdc++.h>
using namespace std;
string solve(string S, string T, string R){
   int x;
   string res = "";
   for (int i = 0; R[i] != 0; i++){
      x = 0;
      for (int j = 0; j < 26; j++){
         if (R[i] == S[j]){
            res += T[j];
            x = 1;
            break;
         }
         else if (R[i] + 32 == S[j]){
            char k = T[j] - 32;
            res += k;
            x = 1;
            break;
         }
      }
      if (x == 0)
         res += R[i];
   }
   return res;
}
int main(){
   string S = "qwertyuiopasdfghjklzxcvbnm";
   string T = "veamhjsgqocnrbfxdtwkylupzi";
   string R = "helloworld87nicecoding";
   cout << solve(S, T, R) << endl;
}

輸入

"qwertyuiopasdfghjklzxcvbnm", "veamhjsgqocnrbfxdtwkylupzi",
"helloworld87nicecoding"

輸出

xawwqeqmwr87zglalqrgzf

更新於:2022年4月8日

400 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告