string

Is it possible to access a word from a string containing more than one word.??
Yes, std::string has several member functions that facilitate this. Do you have a specific example in mind?
actually i wanted to count the number of words which start with character 's' in the following statemens.
It is new.It is singular.
It is simple.It must succeed!
the below code counts the no. of 's' but not the words starting with 's'.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s;
    string s1("s");
    int count=0;
cout<<"enter the text:";
getline(cin,s);
cout<<"\n\nthe text is:"<<s;
for(int i=0;i<s.length();i++)
{
        if(s.at(i)==s1.at(0))
        {
                             count++;
        }
}
cout<<"\n\nno. of words with starting char.'s' is:"<<count;
system("pause");
}
        
                             

On Line 12 you are testing against the entire string with that loop; you'll want to drop the loop and only test the first character.
I don't think the loop on line 12 needs to be dropped?

But additional logic needs to be added so that the test on line 14 is only applied to the first letter in each word. So the question is now to spot the begining of a word. isspace, isalpha, ... might help here?
http://www.cplusplus.com/reference/cctype/isalpha/
http://www.cplusplus.com/reference/cctype/isspace/

Another approach would be to use istringstream
http://www.cplusplus.com/reference/sstream/istringstream/

Andy

PS I don't see the point of a single character string. Why not use a char?
Last edited on
How can i test the first character of each word through my above logic??
You can't with you current logic; as I just said, you need more logic!

Think about what results you get from isalpha() as you scan the string and hopefully you can come up with a strategy yourself (how do you spot the start of words when you read text?)

Andy
Topic archived. No new replies allowed.