954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

comparing strings (newbie question)

Hello,

I'm wanting to know whats in the string and where: I've got this code

string s1="HelloWorld";

if(s1[5] = "W")


now then if i want to know if World is in the string. I've tried doing:

the if....

but it errors:
: error C2446: '==' : no conversion from 'char *' to 'const char *(__thiscall std::basic_string,class std::allocator >::*'
There is no context in which this conversion is possible

: error C2040: '==' : 'const char *(__thiscall std::basic_string,class std::allocator >::*' differs in levels of indirection from 'char [2]'
Error executing cl.exe.

Acidburn
Posting Pro
511 posts since Dec 2004
Reputation Points: 12
Solved Threads: 5
 

Hello,

I'm wanting to know whats in the string and where: I've got this code

string s1="HelloWorld";

if(s1[5] = "W")

now then if i want to know if World is in the string. I've tried doing:

the if....

but it errors:

#include <iostream>
#include <string>

int main()
{
	std::string ex = "Hello World";

	if (ex[6] == 'W')
		std::cout << "W exists in the string." << std::endl;
	std::cout << "Press enter to exit." << std::endl;
	std::cin.get();

	return 0;
}
JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

My book of C++ programming says that, "The relational operators can be applied to variables of type string. Variables of the type string are compared character-by-character, starting with the first character" (C++ Programming: From Problem Analysis To Program Design, Malik, Page 148)
Randy

shortLived
Newbie Poster
15 posts since Aug 2005
Reputation Points: 11
Solved Threads: 0
 
std::string s1="HelloWorld";
if(s1.find("World",0) != std::string.npos) {
  printf("found");
}
else {
  printf("not there");
}
Nedals
Light Poster
43 posts since Dec 2005
Reputation Points: 11
Solved Threads: 0
 
My book of C++ programming says that, "The relational operators can be applied to variables of type string. Variables of the type string are compared character-by-character, starting with the first character" (C++ Programming: From Problem Analysis To Program Design, Malik, Page 148) Randy

Correct, however, this isn't what the code is doing - s[5] returns a char and not a std::string.

"W" with double quotes is of type const char* (a pointer to the first element of a string literal)

if you were to do s[5] == 'W' then this comparison would be ok. The difference being that 'W' with single quotes is also of type char.

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You