A
A
andrey_levushkin2018-10-18 21:27:23
C++ / C#
andrey_levushkin, 2018-10-18 21:27:23

How to count spaces in a string?

There is a string entered from the keyboard
1 2 3 abc
Stored in the variable test
How to calculate how many spaces are in this string and put the result in a variable?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
xoo, 2018-10-18
@andrey_levushkin

#include <stdio.h>
#include <string.h>

int main(){

        char s[] = "2 3 1 2 3 1 2 3";
        char key = '\x20';
        char *p;
        int result = 0;

        p = strchr(s, key);

        while(p != NULL){
                result++;
                p = strchr(p + 1, key);
        }

        printf("%d\n", result);

        return 0;
}

S
Sergey Gornostaev, 2018-10-18
@sergey-gornostaev

char str[100];

fgets(str, 100, stdin);
    
int i, qnt = 0;
for (i = 0; str[i] != '\0'; i++)
    if (str[i] == ' ')
        qnt++;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question