How to count the number of spaces in a string in C++
hello everyone, in the previous tutorial we learned how to count the number of lines in a text file in C++, in this tutorial we will learn about how to count the number of spaces in a string in C++. Let’s see an example, suppose I’m entering a string like Hello everyone, I’m Raj Gaurav.
In the given string the spaces are 4.
but how can we find this with the help of c++ code?
let’s see the source code:
Source code: how to count the number of spaces in a string in C++
#include<iostream> #include<string> using namespace std; int main() { string s; int a,i,count=0; cout<<"Enter The String: "; getline(cin,s); a=s.size(); for(i=0;i<a;i++) { if(s[i]==' ') { count++; } } cout<<" The Number Of Spaces In The String: "<<count; return 0; }
in this above piece of code we use getline() function. getline() function is a c++ liabrary function, used to read a line.
we also use count() that returns the number of occurrence of an element in a given range.
general synatx of getline(): getline(char *string, int length, char deliminator).
getline() is present in the <string> header, The return type of getline() function is also of type istream.
in this code we also use For() loop. if you don’t know how to use for loop read here: how to terminate a loop
output: Enter The String: My name is Raj Gaurav. The Number Of Spaces In The String: 4.
Also read how to create a Text file, Open and Read: File Handling.
Do let me know in the comments section if you have any doubts.
Leave a Reply