10

I am trying to replace a certain character in a string with a space using the following code line:

str[i] = " "; 

How can realize this without getting the error in the title of the question?

1
  • I'll assume C++, since you didn't say. Commented Nov 10, 2011 at 19:24

2 Answers 2

21

use single quotes

str[ i ] = ' '; 

In C++, the token " " is a string literal which represents an array of two characters: the value of a space in the character set (eg, the value 32 in ascii) and a zero. On the other hand, the token ' ' represents a single character with the value of a space (usually 32). Note that in C, the token ' ' represents an integer with the value of a space. (In C, sizeof ' ' == sizeof(int), while in C++, sizeof ' ' == sizeof(char) == 1.)

Sign up to request clarification or add additional context in comments.

Comments

5

Single char literals are obtained with single quotes:

str[i] = ' '; 

A literal with double-quotes is a full string literal (a null-terminated array of char), but you're only replacing a single char.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.