1. 统计数字字符个数 strlen
描述
输入一行字符,统计出其中数字字符的个数。
输入
一行字符串,总长度不超过255。
输出
输出为1行,输出字符串里面数字字符的个数。
样例输入
Peking University is set up at 1898.样例输出
4
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int count = 0;
char s[256];
cin.getline( s, sizeof(s) );
for( int i=0; i<strlen(s); i++ )
{
if( s[i]>='0' && s[i]<='9' )
count++;
}
cout << count;
return 0;
}
char buf[];
cin.getline( char buf[], int bufsize );
//读入一行(包括空格)【行长度不超过bufsize-1】或bufsize-1个字符到buf,自动添加'\0'。回车换行符不会写入buf,但是会从输入流中去掉。
strlen()包含在头文件<cstring>或<string.h>中
2. 找第一个只出现一次的字符
描述
给定一个只包含小写字母的字符串,请你找到第一个仅出现一次的字符。如果没有,输出no。
输入
一个字符串,长度小于100000。
输出
输出第一个仅出现一次的字符,若没有则输出no。
样例输入
abcabd样例输出
c
解析:
用cin.getline()将所有字符读入到char数组中,用count[]数组记录26个字母每个字母出现的次数。
读入结束后,从头开始遍历这一数组,将读到的字母减去'a'存在相应的count[]数组中(也就是说,读到'a'的时候,count[0]+1,同理读到'z'的时候,count[25]+1,所以count[]数组下标从0-25分别对应的就是小写字母a-z,数组的值即对应字母的出现次数)。
遍历完成后,再次从头遍历这一字符串,判断
count[ s[i]-'a' ]
是否等于1,等于1则当前字母就是要输出的字母,且循环结束,否则继续向后寻找。
Q:为什么不是遍历count[]数组?
A:从头开始遍历count[]数组不能保证输出的是“输入字符串中第一个只出现一次的字符”,只能说是字典序最小的只出现一次的字符。
代码1:【超时】
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s[100001];
int count[26];
cin.getline( s, sizeof(s) );
for( int i=0; i<strlen(s); i++ )
count[ s[i] - 'a' ] ++;
for( int i=0; i<strlen(s); i++ )
{
if( count[ s[i]-'a' ] == 1 )
{
cout << s[i];
return 0;
}
}
cout << "no" << endl;
return 0;
}
代码2:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main(){
char s[100000];
int len;
int letter[26];
bool flag=0;
cin.getline(s, sizeof(s));
len=strlen(s);
for(int i=0;i<len;i++){
letter[s[i]-'a']++;
}
for(int i=0;i<len;i++){
if(letter[s[i]-'a']==1){
cout << s[i] << endl;
flag=1;
break;
}
}
if(flag==0){
cout << "no" << endl;
}
return 0;
}
代码一超时原因:
strlen()没有额外存在一个变量里,导致每次循环都要额外计算一遍strlen(),当数组长度很大时,计算会超时,将代码一修改如下即可。
当然加了flag做是否有输出可以。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s[100001];
int count[26];
cin.getline( s, sizeof(s) );
int len = strlen(s);
for( int i=0; i<len; i++ )
count[ s[i] - 'a' ] ++;
for( int i=0; i<len; i++ )
{
if( count[ s[i]-'a' ] == 1 )
{
cout << s[i];
return 0;
}
}
cout << "no" << endl;
return 0;
}