华为刷题
HJ1 字符串最后一个单词的长度
注意cin读取字符串会在空格后停止。用getline(cin,s)可以读取整行
#include <algorithm>
#include <iostream>
#include<string>
using namespace std;
int main() {
string s;
getline(cin,s);
reverse(s.begin(), s.end());
int cnt=0;
for(int i = 0 ; i < s.size(); i ++)
{
if(s[i]!=' ')
cnt++;
else break;
}
cout<<cnt<<endl;
}
HJ2 计算某字符出现次数
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
string s;
getline(cin,s);
char c;
c=getchar();
int cnt=0;
if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
{
if(c>='A'&&c<='Z')
c='a'+c-'A';
for(char &ch:s)
{
if(ch>='A'&&ch<='Z')
ch = 'a'+ ch-'A';
if(ch==c)
cnt++;
}
}
else {
for(auto ch:s)
{
if(c==ch)
cnt++;
}
}
cout<<cnt<<endl;
}
// 64 位输出请用 printf("%lld")
<cctype>头文件提供了以下常用函数:
#include <cctype>
#include <iostream>
int main() {
char upper = 'A';
char lower = 'a';
// 转换为小写
std::cout << "转换为小写: " << char(tolower(upper)) << std::endl; // 输出 'a'
// 转换为大写
std::cout << "转换为大写: " << char(toupper(lower)) << std::endl; // 输出 'A'
// 判断字符类型
std::cout << "是否为字母: " << isalpha('A') << std::endl; // 输出 1 (true)
std::cout << "是否为数字: " << isdigit('5') << std::endl; // 输出 1 (true)
std::cout << "是否为空白字符: " << isspace(' ') << std::endl; // 输出 1 (true)
return 0;
}
注意事项:
- 这些函数的参数是
int类型,内部处理时将字符视为 ASCII 值 - 返回值也是
int类型,通常需要显式转换回char类型 - 这些函数只对英文字母有效,对其他字符无影响
HJ4 字符串分隔
str.append(count, '0');//向str后补count个'0'
str.substr(i,8);//从i下标开始截8个
append()参数是字符串或字符指针,如果只往尾部添加一个字符,用push_back或+=

浙公网安备 33010602011771号