Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Accessing a string by array

string array

  • Please log in to reply
3 replies to this topic

#1 Saint

Saint

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 63 posts

Posted 27 September 2006 - 06:00 AM

I get an error when using this code:

string str = "ahe string";
str[0]='T'; 

it says the indexer is read only. How can I accomplish the same thing?
  • 0
Hi >> Saint

#2 TcM

TcM

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 7563 posts

Posted 27 September 2006 - 10:21 AM

Shouldnt you declare the array like pascal or so? I dont know coz i dont C# but just a curiosity!
  • 0

#3 brackett

brackett

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 192 posts

Posted 27 September 2006 - 12:54 PM

Yeah, Strings in .NET are immutable - you can't change them without creating a new String. So, if you attempted to change one of the characters, you'll have a new string - but no reference to it.

What you want to do is declare a char array, and convert the string to a char array. Then you can change the individual characters:
string str = "ahe string";
char[] c = str.ToCharArray();
chr[0] = 't';

string newstr = new String(chr); // Convert back to string

  • 0

#4 Saint

Saint

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 63 posts

Posted 03 October 2006 - 04:33 PM

Thanks brackett, that worked fine.
  • 0
Hi >> Saint





Also tagged with one or more of these keywords: string, array

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download