C++ compare strings

I am working on a C++ program and am having a problem comparing a string. I need to be able to compare a string in two different ways.
1st
if (stringvariable == "[23]laptop")
I am having a problem with the brackets, it will not allow me to compare with the brackets.
2nd
stringvariable = "1stlaptop";
if (stringvariable == "*laptop")
so when I need to compare a partial name.
I need to be able to do both types of comparisons in LINUX.
georgopanosAsked:
Who is Participating?
 
CSecurityCommented:
If stringvariable is std::string you need to do it like this:

if (stringvariable.compare("[23]laptop") == 0 )

if you want to compare with char array you need:

if (stringvariable.compare(laptop) == 0)

I assuem laptop is char array or string variable
0
 
CSecurityCommented:
It's std::string or char array? that's not correct way to compare... For char arrays you need strcmp for strings you need stringvar.compare
0
 
CSecurityCommented:
If stringvariable is a char array

You need

if (strcmp(stringvariable, "[23]laptop") == 0)

or to compare with another char array:

if (strcmp(stringvariable, laptop) == 0)




0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
georgopanosAuthor Commented:
Yes it is a string array that I am actually using. What about when it is a partial string I am trying to compare?
0
 
jkrCommented:
It seems that you need regular expression matching. Take a look at http://www.opengroup.org/onlinepubs/000095399/functions/regcomp.html ("regcomp, regerror, regexec, regfree - regular expression matching") for that, an example would be
#include <regex.h>


/*
 * Match string against the extended regular expression in
 * pattern, treating errors as no match.
 *
 * Return 1 for match, 0 for no match.
 */


int
match(const char *string, char *pattern)
{
    int    status;
    regex_t    re;


    if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {
        return(0);      /* Report error. */
    }
    status = regexec(&re, string, (size_t) 0, NULL, 0);
    regfree(&re);
    if (status != 0) {
        return(0);      /* Report error. */
    }
    return(1);
}


//...

if (0 != match(stringvariable,"[23]laptop")) {

 // match found
}

Open in new window

0
 
CSecurityCommented:
What do you mean by partial?

For string here it is:

if (stringvariable.compare("[23]laptop") == 0 )


If you mean comparing part of an string variable with an string variable, you need to substring that part of string, put that into new string variable and compare it, like this:



  string temp;

  temp = partialstring.substr (from,to);
then compare it with your string.

stringvariable.compare(partialstring) == 0
0
 
CSecurityCommented:
You can also use strncmp

Like

stringvariable.strncmp (str[n],"partialstring",2) == 0)

it will check 2 char of it, means pa

But if your string is in middle of another string, simple use substr
0
 
peetmCommented:
Why use the std::string.compare() method instead of of using ==
0
 
georgopanosAuthor Commented:
CSecurity:

this worked perfect, exactly what I needed
if (stringvariable.compare("[23]laptop") == 0 )

What I also need is for partial string, I have an string array
stringarray[23] which = "[1234]laptop" for example
i want to compare it by using something like an * before it
if(stringarray[23]=="*laptop");
I do not want to sub string that variable first. I may not know what is in it that variable.
0
 
georgopanosAuthor Commented:
CSecurity:

Could you give me a little more explanation on this comparison.

stringvariable.strncmp (str[n],"partialstring",2) == 0)
0
 
jkrCommented:
As I wrote above - if you want to match regular expressions, use what I pointed out in http:#26203976
0
 
georgopanosAuthor Commented:
jkr
I am trying to follow your code above but unfortunately since I have not used any comparison code like you have written above I am having a little difficult time with it. I have never used match nor regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB). If you could comment the code that would be of great help.
0
 
jkrCommented:
Check the manpage I linked above, the snippet is taken from there ;o) - I just added your specific code to the example.

There are a lot more ways to do regex comparison, e.g. Boost's regex (http://www.boost.org/doc/libs/1_41_0/libs/regex/doc/html/index.html), but the above comes with gcc and is the least amount of overkill.
0
 
phoffricCommented:
re: stringvariable = "1stlaptop";     if (stringvariable == "*laptop")

Here you are asking whether "laptop" is a substring in stringvariable. The function that handles that is strstr.

See http://www.cplusplus.com/reference/clibrary/cstring/strstr/

Shown below is sample code. You can test the return value of strstr() to see if the substring was found. If not found, then it returns a null pointer.




char * stringvariable = "1stlaptop";
if ( NULL != strstr(stringvariable, "laptop") ){
	printf("laptop is in %s\n", stringvariable);
}
else{
	printf("laptop is not in %s\n", stringvariable);
}

Open in new window

0
 
georgopanosAuthor Commented:
phoffric:

from what I see this is in C not C++ I am trying it in C++ and part of the problem is I cannot use the first line from which is taking a string into a char. I am comparing string not char variables. What changes are necessary for this to work in C++
0
 
jkrCommented:
>>Here you are asking whether "laptop" is a substring in stringvariable.

Won't work, since it would also detect "blahlaptopblub" as a valid string, not only "1laptop" and "2laptop"...
0
 
phoffricCommented:
The above is C or C++. But since you are not using char*, then here is how to convert:
string str = "Hello laptop world";
const char * stringvariable = str.data() ;
if ( NULL != strstr(stringvariable, "laptop") ){
	printf("laptop is in %s\n", stringvariable);
}
else{
	printf("laptop is not in %s\n", stringvariable);
}

Open in new window

0
 
jkrCommented:
substring search != regular expressions
0
 
phoffricCommented:
jkr - But the 2nd problem: if (stringvariable == "*laptop")
can be transformed to a substring problem w/o using regular expressions.
0
 
phoffricCommented:
To avoid converting string to char*, you can do the following:
string str = "Hello laptop  world";

if( str.find("laptop") != string::npos ) {
	cout << "laptop is in " << str << endl;
}
else{
	cout << "laptop is NOT in " << str << endl;
}

Open in new window

0
 
phoffricCommented:
re: [23]laptop
To handle this without using regular expressions, you could use following approach. Not sure how you want to generalize your example. Is your prefix always a single char? If so, then you could define a function which takes a string prefix that is defined as "23", for example, and then check to see whether your primary string (laptop) is in the test string, and if it is, then see whether the preceding char is in the input prefix.
size_t found;
string str3 = "Hello blabla3laptop  world";
string str0 = "Hello 1stblalaptop  world";
string strNONE = "Hello world";
string str = str3;

found = str.find("laptop");
if( found != string::npos ) {
	if(found == 0)
	{
	   cout << "laptop is in " << str << " at postition " << found << endl;
	}
	else {
      char prefix = str[found-1];
	  if( prefix == '2' || prefix == '3' ){
	    cout << "[23]laptop found at position " << found-1 << endl;
	  }
	  else
	    cout << "[23]laptop NOT found in " << str << endl;
	}
}
else{
	cout << "laptop is NOT in " << str << endl;
}

Open in new window

0
 
jkrCommented:
So you want to create 3 different solutions for one problem?
0
 
phoffricCommented:
The author identified two problems, which if limited to those two types in the narrowest sense, can be reduced to a single function test. If the two problems are representative of a general regex type problem, then naturally regular expressions is the best general solution.

But see http:#26204223, where author is asking for elaboration.

It may also be that the domain of the problem is restricted to a limited type problem. If author wants to truly generalize, then it is worthwhile to learn regular expressions. If limited domain, then an adhoc solution may be enough to get by.
0
 
georgopanosAuthor Commented:
Worked Great thanks to all who helped....
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.