Naruto
Naruto

Reputation: 9634

String insertion problem in c#

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,"&lt;");
   }

please tell me the solution

Upvotes: 1

Views: 197

Answers (6)

shahkalpesh
shahkalpesh

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

Kristof Claes
Kristof Claes

Reputation: 10941

I think you might be better of with a Replace instead of an Insert:

strCellContent = strCellContent.Replace("<", "&lt;");

Maybe doing Server.HtmlEncode() is even better:

strCellContent = Server.HtmlEncode(strCellContent);

Upvotes: 2

Jon Skeet
Jon Skeet

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

Cheng Chen
Cheng Chen

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,"&lt;");  //string is immutable
}

Upvotes: 0

Rhapsody
Rhapsody

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,"&lt;");
} 

Upvotes: 1

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22064

The return value contains the new string that you desire.

strCellContent = strCellContent.Insert(pos,"&lt;");

Upvotes: 7

Related Questions