Let's say we have string t
.
Why does the following not work:
for (int i = 0; i < t.length; t++)
{
t.charAt(i)+=3;
}
Let's say we have string t
.
Why does the following not work:
for (int i = 0; i < t.length; t++)
{
t.charAt(i)+=3;
}
You didn't mention your programming language.
I assume you are using C#. In C# you cant alternate a string. You can only create new ones. Therefore t.charAt is readonly and cant be alternated with your += operation. If you want to do somehting like this, use a char array or the StringBuilder class.
Edit: .NET doesn't have a method string.charAt() so it seems you are using another programming language. But i think its the same problem.
Because charAt
returns a value, not a reference. The only language I'm aware of where you can assign to the return value of a function is C++ and there you can only do it if the function returns a reference.
You can do char c = t.charAt(3); c += 3;
however this will only change the value of the variable c, it will not change t.
In order to change t you'd need something like t.setCharAt(3, t.charAt(3)+3);
or t[3] += 3;
, however since in most modern OO languages (like Java or C#) strings are immutable methods like setCharAt
don't exist.
As Marks mentioned, you didn't mention your programming language. For most programming languages, you cannot assign to the return value of a function (and +=
is an assignment). C++ is an exception, but given the name of your method (charAt
), it looks like you're using Java or perhaps C#. To set the character, you will need to use some kind of a setChar
method, if strings can be mutated. In both Java and C#, strings are immutable, so they cannot be changed once they have been created. Your only choice is to create a new string containing the transformed characters.
So, there are several reasons, assuming Java or C#, why the code doesn't work:
If you're talking about Java, it's because the +=
operator is an assignment operator and you'd be trying to assign a value to a value returned from a method call.
Instead of trying to manipulate the String directly in this way, get a character array and manipulate that. Then create a new String with the resulting array.
The String class is immutable -> you can't modify a string instance.
You'll see that string methods doesn't modify the current instance but only creates a new string.
For exemple string.toLowerCase() will keep string the same and return a new string instance...
And other reasons, it's not correct because charAt returns a primitive type It's like writing something like: 3 = 5+2 Do you mean the new value of 3 is 7 ? So then when you do 3+1 it returns 8? :D