Reputation: 9634
I am trying to insert a string at a position for C# string, its failing
here is the snippet.
if(strCellContent.Contains("<"))
{
int pos = strCellContent.IndexOf("<");
strCellContent.Insert(pos,"<");
}
please tell me the solution
Upvotes: 1
Views: 197
Reputation: 33476
As others have explained with the code, I will add that
The value of the String object is the content of the sequential collection, and that value is immutable (that is, it is read-only). For more information about the immutability of strings, see the Immutability and the StringBuilder Class section.
from: http://msdn.microsoft.com/en-us/library/system.string.aspx
Upvotes: 0
Reputation: 10941
I think you might be better of with a Replace
instead of an Insert
:
strCellContent = strCellContent.Replace("<", "<");
Maybe doing Server.HtmlEncode()
is even better:
strCellContent = Server.HtmlEncode(strCellContent);
Upvotes: 2
Reputation: 1499760
Gunner and Rhapsody have given correct changes, but it's worth knowing why your original attempt failed. The String type is immutable - once you've got a string, you can't change its contents. All the methods which look like they're changing it actually just return a new value. So for example, if you have:
string x = "foo";
string y = x.Replace("o", "e");
the string x
refers to will still contain the characters "foo"... but the string y
refers to will contain the characters "fee".
This affects all uses of strings, not just the particular situation you're looking at now (which would definitely be better handled using Replace
, or even better still a library call which knows how to do all the escaping you need).
Upvotes: 7
Reputation: 43513
.Contains
is not a good idea here, because you need to know the position. This solution will be more efficient.
int pos = strCellContent.IndexOf("<");
if (pos >= 0) //that means the string Contains("<")
{
strCellContent = strCellContent.Insert(pos,"<"); //string is immutable
}
Upvotes: 0
Reputation: 6077
When I look at your code I think you want to do a replace, but try this:
if(strCellContent.Contains("<"))
{
int pos = strCellContent.IndexOf("<");
strCellContent = strCellContent.Insert(pos,"<");
}
Upvotes: 1
Reputation: 22064
The return value contains the new string that you desire.
strCellContent = strCellContent.Insert(pos,"<");
Upvotes: 7