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
  • Milan may have a point. An implementation of strcmp attributed to PJ Plauger is:

    int strcmp (const char * s1, const char * s2)
    {
        for(; *s1 == *s2; ++s1, ++s2)
            if(*s1 == 0)
                return 0;
        return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
    }
    

    So if the null terminator of s1 is encountered before a difference is detected with s2, the strcmp will return 0. So, flipping the order of the arguments to strcmp might be one solution.

    The web page I found this on is here: strcmp

Reply
  • Milan may have a point. An implementation of strcmp attributed to PJ Plauger is:

    int strcmp (const char * s1, const char * s2)
    {
        for(; *s1 == *s2; ++s1, ++s2)
            if(*s1 == 0)
                return 0;
        return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
    }
    

    So if the null terminator of s1 is encountered before a difference is detected with s2, the strcmp will return 0. So, flipping the order of the arguments to strcmp might be one solution.

    The web page I found this on is here: strcmp

Children
Related