Does the immutable principle still apply when manipulating a char in a string?
If I manipulate a specific开发者_开发百科 char off of a string, would it still be considered as a string manipulation internally by CLR, resulting in temporary string creation?
For example :
string myString = "String";
myString[0] = 's';
How about creating a char array[] eqvivalent of the string being edited and perform all position specific manipulation on that and transform it back to string.
Would it help cutting no of temp strings at least to just 2 actual string manipulations?
This code doesn't compile:
error CS0200: Property or indexer 'string.this[int]' cannot be assigned to -- it is read only
That's because strings are immutable, as you said.
For the purpose of modifying a string, you need to use StringBuilder
class (a mutable string for all intents and purposes), that has read-write this[int]
property.
StringBuilder builder = new StringBuilder("Sample");
builder[0] = 's'; //produces "sample"
It is probably worth mentioning that although strings are considered immutable in normal usage, it is actually possible to mutate them. If you configure a VS project to "allow unsafe code", you can then use unsafe code to mutate a string:
internal class Program
{
private static void Main()
{
const string SomeString = "hello";
Console.WriteLine("Original string:'{0}'.", SomeString);
unsafe
{
fixed (char* charArray = SomeString)
{
byte* buffer = (byte*)(charArray);
buffer[0] = 66;
buffer[2] = 76;
buffer[4] = 73;
buffer[6] = 78;
buffer[8] = 71;
}
}
Console.WriteLine("Mutated string:'{0}'.", SomeString);
}
}
This could be considered as pretty evil, but it does have its uses, e.g. .NET Regular expressions on bytes instead of chars.
Strings are immutable. You cannot change individual chars. The indexer operator on strings is read-only, so you will get an error if you try to assign using array style index on a string.
精彩评论