This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Creating a string from a character array

Hi all,

I would like to use the strcmp - string compare function, however don't know how to create a string from character array. Standard way would be something like this:

char arr[ ] = "Hello World";
string str(arr);

However the compiler doesn't like the type string. Is there a way to create a string that I could use such as in the following example?

if(strcmp("Hello World",str) == 0)
{do something}

Regards

Milan

Parents
  • Hi Milan, perhaps your C platform is buggy, or maybe there's something else going on in your test case, but strcmp should not tell you a string matches an initial sub-string.

    Given a compliant strcmp implementation (as in John's example, or the standard C library), the code snippet:

    char buf[BUFSZ];
    
    strcpy (buf, "rat");
    (void) printf ("%s %s rate\n", buf, (strcmp (buf, "rate")) ? "!=" : "==");
    strcpy (buf, "rate");
    (void) printf ("%s %s rate\n", buf, (strcmp (buf, "rate")) ? "!=" : "==");
    strcpy (buf, "rated");
    (void) printf ("%s %s rate\n", buf, (strcmp (buf, "rate")) ? "!=" : "==");
    

    should produce:

    rat != rate
    rate == rate
    rated != rate
    

    The return 0 in the strcmp example John posted is hit only when *s1 == *s2 and *s1 == 0, so *s2 == 0 as well. The for loop exits on the first difference and returns non-zero, so regardless of operand order that code will return 0 only when the two strings are identical.

  • Honestly I tried to assign a NULL values into the buffer and it did not work. Now, I have done it properly using memset and it seems to be working fine.

    memset(p_data, 0, length);
    

    Thank you.

Reply Children
No Data
Related