1.计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)
贴代码
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
getline(cin, str);
int count = 0;
int end = str.length() - 1;
while (end >= 0 && str[end] != ' ')
{
end--;
count++;
}
cout << count;
return 0;
}
2.计算某字符出现次数
#include<iostream>
#include<string>
using namespace std;
int main(){
string str;
char s;
int count = 0;
getline(cin, str);
cin >> s;
if(s > 64)
{
for (int i = 0; i < str.length(); i++)
{
if (str[i] == s || str[i] + 32 == s || str[i] - 32 == s)
{
count++;
}
}
}
else
{
for (int i = 0; i < str.length(); i++)
{
if (str[i] == s)
{
count++;
}
}
}
cout << count;
return 0;
}
3.明明的随机数
/*
int n,num;
int arr[500] = { 0 };
while (cin>> num)
{
for (int i = 0; i < num; i++)
{
cin >> n;
arr[n] = 1;
}
}
for (int j = 0; j <= 500; j++)
{
if (arr[j] == 1)
{
cout << j << endl;
}
}
return 0;
*/
//set中的元素会自动排好序,且不允许有重复元素。set函数内部实现的结构是红黑树
int n, num;
set<int> ss;
while (cin >> num)
{
ss.clear();
while (num--)
{
cin >> n;
ss.insert(n);
}
for (set<int>::iterator it = ss.begin(); it != ss.end(); it++)
{
cout << *it << endl;
}
}
return 0;
}
4. 输入一串字符,按长度为8拆分,长度不是8补0
substr有2种用法:
假设:string s = "0123456789";
string sub1 = s.substr(5); //只有一个数字5表示从下标为5开始一直到结尾:sub1 = "56789"
string sub2 = s.substr(5, 3); //从下标为5开始截取长度为3位:sub2 = "567"
#include <string>
#include <iostream>
using namespace std;
int main() {
string str;
while (cin >> str)
{
int len = str.length();
if (len % 8 != 0)
{
int count = 8 - len % 8;
str.append(count, '0');
}
for (int i = 0; i < str.length(); i += 8)
{
cout << str.substr(i, 8) << endl;
}
}
return 0;
}
5.十六进制字符转十进制
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
int main() {
string s;
while (cin >> s)
{
int bit = 0;
int res = 0;
for (int i = s.length() - 1; i> 1; i--)
{
if (s[i] >= '0' && s[i] <= '9')
{
res += (s[i] - '0') * pow(16, bit);
bit++;
}
else if (s[i] >= 'A' && s[i] <= 'F')
{
res += (s[i] - 'A' + 10) * pow(16,bit);
bit++;
}
}
cout << res << endl;
}
return 0;
}