首頁  >  文章  >  後端開發  >  按鍵手機上按下的按鈕數量

按鍵手機上按下的按鈕數量

王林
王林轉載
2023-09-07 09:33:15892瀏覽

按鍵手機上按下的按鈕數量

簡介

C 中的字串是一種內建的儲存結構,用於包含數字、字元甚至特殊符號。每個字串都與一個確定的大小相關聯,由其長度屬性指定。預設情況下,字串位置從 0 開始。字串中的字元可以進行各種類型的操作 -

  • 可以在字串末尾附加新字元。

  • 一個字元可以多次附加到字串中。

在本文中,我們將開發一個程式碼,該程式碼將字串作為輸入,並計算必須按下按鍵的次數,以便將該字串鍵入到鍵盤移動螢幕上。也提供了一個輸入數組,說明任何特定字元的按鍵次數。讓我們看下面的例子來更好地理解這個主題 -

範例

範例 1 - str - “abc”

輸出 - 6

例如,下面的範例字串,按鍵總數相當於 1 2 3 = 6。

在本文中,我們將創建一個解決方案,一次提取字串中的一個字符,然後從輸入數組中提取其相應的按鍵。每次將計數新增至 sum 變數。

文法

str.length()

長度()

C 中的 length() 方法用於計算字串中包含的字母數字字元的數量。它可用於計算字母數字字元、空格以及數字的數量。

演算法

  • 接受輸入字串 str

  • 一個計數器,用於儲存每個字元應被按下以產生字串的次數。

  • 使用 length() 方法計算字串的長度,並將其儲存在 len 變數中

  • 每次提取第i個位置的字符,ch。

  • 計數器以 arr 中提到的次數遞增位置。

  • 執行用計數器值初始化的遞減循環,以將提取的字元附加到輸出字串。

  • 每次計數值都會遞減。

  • 對字元執行所需次數的迭代後,指標會移動到下一個字元。

範例

以下 C 程式碼片段用於根據給定的輸入範例字串建立加密字串 -

//including the required libraries
#include <bits/stdc++.h>
using namespace std;
 
//storing thr reqd number of times a character should be pressed
const int arr[] = { 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4 };

//return the total number of times the button should be pressed
int numkeypresses(string str) {
   //initialising with count 
   int count = 0;
   //count the length of string 
   int len = str.length();
 
   // total key presses
   for (int i = 0; i < len; i++) {
      char ch = str[i];
      count+= arr[ch - 'a'];
   }
    
   cout << "Total number of key presses "<< count;
}
 
// Driver code
int main() {
   //input string
   string str = "tutorials";
   cout <<"Input String : "<< str << "\n" ;
   //calling the function to count the number of times key is pressed 
   numkeypresses(str);
 
   return 0;
}

輸出

Input String − tutorials
Total number of key presses 21

結論

字元和整數使用 ASCII 代碼進行操作。它們的相互轉換可以很容易地模擬,例如,整數可以透過減去字元“a”來轉換為其對應的字元等效值。這導致其 ASCII 代碼相互轉換,可用於字串的數字操作操作。

以上是按鍵手機上按下的按鈕數量的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除