For the Arduino programming environment, let's say I have a string literal:

char strlit[17] = "_ _ _ Sup _ _ team? _ _ _"

I would like to put brackets around the nth word and clear any brackets that may be around current words.

meaning that foo(strlit, 0) would return "_ _[Sup]_team?_ _ _"

and foo(strlit, 1) would return "_ _ _Sup _ [team?] _ _"

Right now the only way I know how to do this would be incrementing through the array, checking to see if the current char isspace() and the previous or next char isgraph()

Something like:

[code]...
char strlit[17] = "   Sup  team?   ";
Find_word_trim(&strlit,1);
...[code]

Where Find_word_trim looks like

     void Menu_Opt(char *line[17], int set)
     {
       int setno;
       bool on_set=false;
       int i = 0;
       while(line[i]!=NULL)
       if(line[i]=='[' || line[i]==']')
       {
         if (line[i]='[')
         {
           setno++;
         }
         line[i]=' ';
       }
       else if(isspace(line[i]) && isgraph(line[i+1])&&!on_set)
       {
         if(setno==set)
         {
           line[i]='[';
           on_set=true;
         }
         else
         {
           setno++;
         }
       }
       else if(isspace(line[i]) && isgraph(line[i-1])&&on_set)
       {
         line[i]=']';
       }
       i++;
     }

Does it. However, I feel like there's a faster way to solve the problem. Any input on how I should optimize or rewrite would be greatly appreciated. I'm ok with the assumption that my strlit will not have a [ or ] char naturally, however, bonus points if you can avoid that assumption

  • "I think would do it." Please make sure this 'does it', and remove language that may imply this code doesn't work as you intend. – Peilonrayz Jul 20 '17 at 14:24
  • oh sorry, yes it does work as intended – ATE-ENGE Jul 20 '17 at 14:31

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.