0
#include <iostream>
#include <string>
/*i want to compare string and char as char is a subset of string*/
string S [50];
//algorithm is somewhat like:
i=0;
while(i<23){
    char c = (char) i;
    S[i] = c;
}
for(i=23;i<50;i++){
    S[i]="hello";
}
//i want to check how many hello are there
i=0;
x=0;
while(i<50){
    if (S[i] = "hello"){
        x++;
        i++;}
    else{
    i++;
    }
//but here is one problem the array elements from 0 to 22 are characters so it cant be compared
//with hello which is a string. to do so i have to convert those characters into strings.         
//code would be somewhat
i=0;
while(i<23){
    c = char(i)
//convert c which is a character into string 
    S[i] = c;
}
3
Contributors
3
Replies
32
Views
2 Years
Discussion Span
Last Post by Vivek_12
0

string's operator == can take a string and a char so all you have to do is:

i=0;
while(i<23){
    c = char(i)
//convert c which is a character into string 
    if (S[i] == c)
     // do something here
}
0

Just a comment, but if you have an array of strings, you can iterate through them with one of the std algorithms to count the ones that you want. So, to count the number of "hello" strings, you can simply do:

auto number_of_hellos = std::count( S.cbegin(), S.cend(), "hello" );

It's generally best to look for a standard algorithm to do something if you can :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.