字符串基础
一、字符串长度
题目描述
输入一个字符串(不含空格),求他的长度(即:包含多少个字符)。
以下三个方法主要是运行时长的区别。
#include<bits/stdc++.h>
using namespace std;
int main()//运行时长3ms
{
int sum=0;
char ch;
while(~scanf("%c",&ch)) sum++;
printf("%d",sum-1);
return 0;
}
#include <iostream>
using namespace std;
int main()//运行时长2ms
{
char c;
int sum=0;
while(scanf("%c",&c)!=EOF)
{
sum++;
}
cout<<sum-1;
}
#include<stdio.h>
#include<string.h>
int main()//运行时长1ms
{
char a[100];
scanf("%s",&a);
int b=strlen(a);
printf("%d",b);
return 0;
}
二、字符串逆序
题目描述
给定一个字符串,然后将字符串逆序输出。
法一:栈(先入后出)
#include<bits/stdc++.h>
using namespace std;
int main(){//运行时长3ms
int n=0;
char ch;
stack<char>s;
while(true){
ch=getchar();
if(ch==' '||ch=='\n'||ch==EOF){
while(!s.empty()){
printf("%c",s.top());
s.pop();
}
if(ch=='\n'||ch==EOF) break;
printf(" ");
}
else s.push(ch);
}
return 0;
}
法二:s.size()求长度
#include <iostream>
#include <cstring>
using namespace std;
int main()//运行时长2ms
{
string s;
cin>>s;
for(int i=s.size()-1;i>=0;i--)//减掉'\0'
{
cout<<s[i];
}
}
法三:
#include <iostream>
using namespace std;
int main()//运行时长1ms
{
char a[105]={};
scanf("%s",a);
int cnt=0;
while(a[cnt]!='\0')
{
cnt++;
}
for(int i=cnt-1;i>=0;i--)
{
cout<<a[i];
}
}
三、字符串查找统计
题目描述
输入一行字符串,输出其中的小写字母,并统计其中小写字母的个数。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int sum=0;
char ch;
while(~scanf("%c",&ch))
{
if((int)ch>=97&&(int)ch<=122)
{
printf("%c",ch);
sum++;
}
}
printf("\n");
printf("%d",sum);
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main()//占用内存较上一个低
{
int cnt = 0;
char s[505];
cin.getline(s, 505);
int n = strlen(s);
for(int i = 0 ; i < n ; i ++)
{
if(s[i] <= 'z' && s[i] >= 'a')//不必须用asc2码判断
{
cout << s[i];
cnt ++;
}
}
cout << endl << cnt;
return 0;
}
#include <stdio.h>//1ms方法
#include <ctype.h> // 需要使用ctype库进行字符判断
int main() {
char line[500];
int count = 0;
fgets(line, 500, stdin); // 使用fgets读取一行字符串,包括空格
// 遍历字符串中的每个字符
for (int i = 0; line[i] != '\0'; i++) {
if (islower(line[i])) { // 使用islower函数判断字符是否为小写字母
printf("%c", line[i]);
count++; // 统计小写字母的个数
}
}
printf("\n");
printf("%d\n", count);
return 0;
}
四、[NOIP2018]标题统计
题目描述
凯刚写了一篇美妙的作文,请问这篇作文的标题中有多少个字符?
注意:标题中可能包含大、小写英文字母、数字字符、空格和换行符。统计标题字 符数时,空格和换行符不计算在内。
#include <iostream>
using namespace std;
int main()
{
char ch;
int b=0;
while(cin>>ch)
{
if(ch!=' '&&ch!='\0')
b++;
}
cout<<b;
}