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<char,struct std::char_traits<char>,class std::allocator<char> >::*'
There is no context in which this conversion is possible

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

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;
}

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

std::string s1="HelloWorld";
if(s1.find("World",0) != std::string.npos) {
  printf("found");
}
else {
  printf("not there");
}

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.

This article has been dead for over six months. Start a new discussion instead.