如何统计字符串的个数

I n d e x Index Index:

因为某人太菜,并不知道如何怎样转化所以就拿来写一下。

定义:

一个变量 = strlen(字符串数组)

c o d e code code

len=strlen(s);

具体应用:

【NOIP2018】标题统计

简单题,但是我还是没得全分,只有四十就是统计字符

80分代码:

#include <bits/stdc++.h>
using namespace std;
char s[1000];
int len, sum = 0;
int main() {
    
    
    cin >> s;
    len = strlen(s);
    for (int i = 0; i < len; i++){
    
    
    	if (s[i] == '\n') break;
        if(s[i] != ' ')  sum ++; 
	} 
    printf("%d\n", sum);

    return 0;
}

因为这个字符串只能读到空格之前所以只能过80%的样例,

所以只能用cin.get来输入

100分代码

#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>

using namespace std;
int main() {
    
    
	char s;
	int i = 0;
	while(cin.get(s)) {
    
    
		if(s == '\n') break;
		if(s!=' ') i ++;
	}
	cout << i << endl;
	return 0;
}

总之,就是那个代码可以转换。。

猜你喜欢

转载自blog.csdn.net/C202207LYX/article/details/108577238