Check an Array String character value without extra variable

84 Views Asked by At

suppose I've this code:

    string str[] = {"devil", "chandra"};
    // check if str[0] has properly devil, character by character  or not without extra variable

Now I want to check str[ 0 ]'s all character which is 'd','e','v','i','l' one by one without extra variable. with extra variable code will be :

string n1 = "devil";

for(int i=0; i<1; i++){
   string s1 = str[i]
   for(int j=0; j<s1.size(); j++){
   if(s1[i] == n[i]){
   cout << s1[i] << " ";
  }
}

Basically, I want O(n) loop where I can access all indexes string and among them all characters.

Like s[ i ] is "devil" and s[[i]] = 'd' something like this, Know it's not valid, but is there any way to do that?? Even I don't know is it a valid question or not!

1

There are 1 best solutions below

0
On

I'm not sure why you would need an extra variable. If you need a conditional that checks that the first value in the array of strings is "devil", it shouldn't be anymore complicated than:

if (str[0] == "devil")
{
    * Do things *
}

C++ can check a standard string all at once. You don't need to check each individual character if that's what you're thinking.

Keep in mind, this isn't going to account for situations where the string is not exactly the same. For instance, if str[0] has "Devil" instead of "devil", then the conditional will evaluate to false.