-4

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!

Chandra Sekhar Bala
  • 190
  • 1
  • 1
  • 12
  • 4
    `str[0] == "devil"`? There is no extra variable, unless internal implementation of `std::string` would use it. – Yksisarvinen Apr 16 '21 at 22:06
  • 2
    @Chandra Sekhar For starters show how you are checking the condition with an extra variable.:) – Vlad from Moscow Apr 16 '21 at 22:24
  • This sounds like a question from some online contest/competition site, that tests whether someone knows how to use iterators and algorithms from the C++ library. Unfortunately, those useless contest sites are just a list of meaningless programming puzzles, without any tutorials or any material that teach or explain the underlying, fundamental C++ concepts. Someone who wants to learn how to answer this kind of a question will only be able to do that after studying C++ [using a good C++ textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), – Sam Varshavchik Apr 16 '21 at 22:42

1 Answers1

2

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.