Karyna
Karyna

Reputation: 205

Check if a string contains a specific number of given values

I am trying to decode a message provided as a morse code via command line argument. If the provided string contains 7 spaces it means that I need to print a space to the decoded string. This is the way I am trying to check if string contains 7 spaces via for loop:

                if ((str[i] == ' ' && str[i + 1] == ' ' &&
                 str[i + 2] == ' ' && str[i + 3] == ' ' &&
                 str[i + 4] == ' ' && str[i + 5] == ' ' &&
                 str[i + 6] == ' ')) {
                mx_printchar(' ');
               }

Please let me know if any efficient way could be used for this purpose. Currently, I cannot use linked lists or structs, but maybe there is any other way, please advise

Upvotes: 0

Views: 40

Answers (1)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

You could use substr() instead as shown below :

if (str.substr(i,7) == "       ") {
     //do your task here
}

This will check for the substring from i to i+7(this index included) and if this substring is equal to 7 spaces, then it will do the required task.

Upvotes: 1

Related Questions