Easier way to compare char arrays?

So, this works:

char ModeTest[2]={'T','S'};
  char ModeOps[2]={'O','P'};
  //strcpy(ModeTest,"TS");
  //strcpy(ModeOps,"OP");
  int isModeTest = strcmp(ModeFlag,ModeTest);
  int isModeOps = strcmp(ModeFlag,ModeTest);

But omigoodness, what a lot of code to do "if this = that." I also had zero luck with strcpy using string literals, although copying actual arrays back and forth works fine.

At any rate, is there a shorter/better way to compare string arrays? Conext: I'm breaking up an incoming serial command into tokens and then selecting code based on the tokens. So lots of ifs.

While we're in the neighborhood: switch doesn't seem to like char arrays. Is that pretty much the case?

I doubt that.
Neither ModeTest nor ModeOps are proper strings.
Both is____ are set to the same value.
ModeFlag is maybe a string, but who knows.

OK, so what's the secret sauce? And I get a weird return for ModeOps[]. Even though I explicitly define it with two chars, it comes back "OPTS" -- I'm in the center of the galaxy where physics has stopped working... clues welcome.

Give a working sketch that illustrates your problem,
I don't understand what you are trying to achieve.

OK, part of it is [2] is an index, not a size.

Not a secret. C-strings require a terminating zero byte. This is a valid C-string:
char ModeTest[3]={'T','S', 0};

So is this
char ModeTest[]="TS";

1 Like

All [2]s in your snippet are sizes, not indices.

I don't quite have a working sketch. Here's what I'm doing functionally:

  1. Read char array from serial line. ex: TS:EN:E1:PT:20. Works fine.
  2. Parse that into several different arrays using strtok. Also works fine. I get five arrays with the proper characters. (TS EN, etc.)
  3. Based on each Token, make a choice. This is where things break down. Pseudo code:
    if ModeTest array = "TS" then do test things.
    if ModeTest array = "OP" then do ops things.

ModeTest is one of the five arrays I copy the tokens into. They work fine, print, write, strcpy to other arrays, all good.

But COMPARING them to something is proving to be difficult.

Understood. So when I declare like this:

char SomeChar[32]

I'm not doing it right?

Who could answer that without context?

Correct the obvious errors in your code, then post a complete example that gives a result you don't understand.

Here is the pasing code that creates the tokens. What I need to do then is say "If ThisToken = ThisValue, then do ThisThing."

void parseData() 
{     
    //MODE FLAG:GROUP PREFIX:ITEM:DATA COMPONENT:DATA
    //TS:EN:E1:PT:20
    
    //Declare array and get first token.
    Token=strtok(receivedChars,":");                

    //Initialize TokenCounter
    TokenCounter=0;
    //Read the rest of the tokens using the same array.  NULL tells strtok that we're still working with the same array.
    while (Token!=NULL)
    { 
      switch (TokenCounter)
      {    
        case 0://We have the first token, so go ahead and avaluate.  We'll get the next one at the END so if it's null, loop exits.          
          strcpy(ModeFlag,Token);
          Serial.print("Mode Flag is: ");
          Serial.println(ModeFlag);              
          TokenCounter++;
        break;
                
        case 1://GroupPrefix
          strcpy (GroupPrefix,Token);
          TokenCounter++;
          Serial.print ("Group Prefix is: ");
          Serial.println(GroupPrefix);                    
        break;
        
        case 2://Item
          strcpy (Item,Token);
          TokenCounter++;
          Serial.print ("Item is: ");
          Serial.println(Item);          
        break;
        
        case 3://Component
          strcpy (Component,Token);
          TokenCounter++;
          Serial.print("Component is: ");
          Serial.println(Component);          
        break;
        
        case 4://Data
          strcpy (Data,Token);
          TokenCounter++; //in case we come across garbage
          Serial.print("Data is: ");
          Serial.println(Data);          
        break;      
            
        default:
        Serial.println("Invalid Data.");
      }      
      Token=strtok(NULL,":");//Getting next token here.      
   }  
 }

Here's output of parser, I print the Token values for each extracted token.

Arduino ready.
Mode Flag is: OP
Group Prefix is: EN
Item is: E1
Component is: PT
Data is: 20

What needs to happen next:
If ModeFlag=OP then do OP stuff.
If ModeFlag=TS then to TS stuff...

The Tokens are parsed to know what code to rune. (Light this diode, spin this wheel, w/e)

You need to learn how to use strcmp(). Plenty of tutorials on line.

Have fun!

That is usually not necessary,
as strtok puts zero chars in place of the parsed delimiters in the original string.
I would use an array of char pointers, holding the results of the strtok.

Well, the reference I found said:

SomeInteger = strcmp(charArray1, charArray2);

If SomeInteger comes back 0, they're the same.

But... not quite working the way I expected./

Probably because: see #6

There is the memcmp function used to compare 2 arrays (blocks of memory). The memcmp function works on arrays that are not null terminated. The size of the memory block is passed as an argument.

And then it doesn’t. By the sheer luck you have next byte after the end of array a 0.

Ah! Very helpful. OK. I thought I tried that last version and it didn't like it. But now compiles fine. I must have dorched something first time.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.