手机按键计数
介绍
在 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