0

I am trying to do the following expression, but I keep running into this exception, "Cannot find property setter for 'chars'."

Here is the expression:

xstr, str : string;
for i := 1 to length(str) do
begin
  if ((i mod 2)<>0) then
  begin
    xstr[i] := char(Ord(str[i]) xor $AA);  <<<<------ Exception Raised
  end
  else
  begin
    xstr[i] := char(Ord(str[i]) xor $55);  <<<<------ Exception Raised
  end;
end;

The value of "str" is passed into the encryption method.

This is part of an encryption method. What is the best way to do this?

Ken White
  • 123,280
  • 14
  • 225
  • 444
ThN
  • 3,235
  • 3
  • 57
  • 115

1 Answers1

5

System.String is an immutable class, meaning you cannot modify instances of it. .NET requires modifying string operations to create new instances of a string. For your purpose, it’s probably easiest and most efficient to create a char array of the modified characters and then construct a string from that.

In general, the System.Text.StringBuilder class offers a mutable string instance.

In fact, even if it weren’t for the immutability of strings, your code would fail because you didn’t allocate a string, so assignment to xstr[i] would yield in a buffer overflow exception. You need to do that when using an array of char.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214