• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 222
  • Last Modified:

Changing an individual character within a string

I've been struggling with this for a while. It's such a simple question that I've been reluctant to ask it.

How do you change an individual character within a string without replace or substring/remove in visual c++ .net?

The .net equivalent of :

st[index] = '\newvalue';

I have to use this method because the file I have a problem with needs extra carriage returns filtered out of it and the newline/carriage return's that are in the right place left alone.

I thought about this:
arbSt = mainSt->Substring(indexOfExtraCrLf - 10, 20); // arbitrary length to make sure replace doesn't replace everything
tmpSt = mainSt->Substring(beginning - 10, 20)->Replace("\r\n", " ");
mainSt->Replace(arbStr, tmpSt);

That would work, but I'd rather know a better way so I don't end up doing that for every typo within my source file.

Thanks!

_david
0
_davidharris
Asked:
_davidharris
  • 3
  • 2
1 Solution
 
AlexFMCommented:
.NET string object is immutable, this means, it's value cannot be changed once it is created. Functions like Trim, Replace, Substring return new string instance and don't change original string.
0
 
_davidharrisAuthor Commented:
Is there a way to change that string into an array of bytes and then change the byte value, and then convert (or dump the byte array to a file) the byte array to a string?

_david
0
 
AlexFMCommented:
String to char array: see String.CopyTo method.
Char array to string: see string constructor
String (array<wchar_t>^ value)
0
 
_davidharrisAuthor Commented:
I just ended up using replace and substring. Thanks for your help!

_david
0
 
_davidharrisAuthor Commented:

                       // check each field for characters that are not alphanumeric or punctuation
             for (char_i = 0; char_i != field->Length; char_i++)
                   if (!(Char::IsLetterOrDigit(field[char_i]) || Char::IsPunctuation(field[char_i])))
                         field = field->Replace(field[char_i], ' ');
      
That's what I ended up with! Which works just the same.

_david
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now