手機按鍵計數
介紹
在 C++ 中,字串是一種內建儲存結構,用於儲存數字、字元甚至特殊符號。每個字串都具有確定的長度屬性來指定其大小。預設情況下,字串位置從 0 開始。字串中的字元可以進行各種型別的操作:
可以在字串末尾追加新字元。
可以將一個字元多次追加到字串中。
在本文中,我們將開發一個程式碼,該程式碼以字串作為輸入,並計算在手機按鍵螢幕上鍵入該字串所需的按鍵次數。還提供了一個輸入陣列,用於說明任何特定字元的按鍵次數。讓我們來看下面的例子,以便更好地理解這個主題:
示例
示例 1:str - “abc”
輸出 - 6
例如,對於以下示例字串,總按鍵次數等於 1+2+3 = 6。
在本文中,我們將建立一個解決方案,一次提取字串的一個字元,然後從輸入陣列中提取其對應的按鍵次數。每次將計數新增到 sum 變數中。
語法
str.length()
length()
C++ 中的 length() 方法用於計算字串中包含的字母數字字元數。它可以用於計算字母數字字元、空格以及數字的數量。
演算法
接受輸入字串 str
維護一個計數器 count,用於儲存生成字串所需的每個字元的按鍵次數。
使用 length() 方法計算字串的長度,並將其儲存在 len 變數中
每次提取第 i 個位置的字元 ch。
根據 arr 中提到的次數遞增計數器的值。
執行一個以計數器值為初始值的遞減迴圈,將提取的字元追加到輸出字串。
每次 count 值遞減。
在對字元進行所需次數的迭代後,指標移到下一個字元。
示例
以下 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 碼的相互轉換,可用於字串的數值操作。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP