user4439720
user4439720

Reputation: 11

VC++ How to change a character at a specific position within a string?

Visual C++: I want to set the 3rd character in a string to 'C'.

If I try

String^ s1="XXXXXX";
s1[2]="C";

The compiler says:

'System::String::default': property does not have a 'set' method

Any idea?

Upvotes: 1

Views: 712

Answers (3)

Hans Passant
Hans Passant

Reputation: 941357

The System::String type is immutable, an expensive word that just means that it doesn't have a single method or property that lets you change the string after it is created. That gives the type very desirable behavior. It is always thread-safe and you can readily pass a string to a function without having to worry that the function is going to change it. Or in other words, it behaves like a value, just like an int.

But the other side of the medal is that it won't let you do what you want to do, the compiler reminds you that it isn't possible. You have to create a new string object. The Microsoft.VisualBasic namespace has a convenience method for that, but everybody gets their underwear in a bundle when they see that name. So write it explicitly:

  String^ s1="XXXXXX";
  s1 = s1->SubString(0, 2) + 'C' + s1->SubString(3);

Or more universally:

  String^ ReplaceAt(String^ str, String^ subst, int index)
  {
      return str->Substring(0, index) + subst + str->Substring(index + subst->Length);
  }

If you are doing at lot of this, repeatedly creating string objects isn't very cheap, then you want to use a StringBuilder instead.

Upvotes: 3

Gabriel
Gabriel

Reputation: 3584

you can do the conversion in the native string and convert it back to managed string.

#include <msclr\marshal_cppstd.h>

System::String^ managed = "XXXXXX";
std::string unmanaged = msclr::interop::marshal_as<std::string>(managed);

unmanaged[2]='C';

System::String^ managed2 = String(unmanaged.c_str());

Hope that helps,

Upvotes: 0

Mr.C64
Mr.C64

Reputation: 42924

C++/CLI String's are immutable, so once created you can't change their content, as your error message suggests.

The s1[2]='C'; syntax (note the single quote around the character C, not double quote) would work fine for standard C++ std::string.

Upvotes: 1

Related Questions