how do I set a character at an index in a string in c#?
If it is of type string
then you can't do that because strings are immutable - they cannot be changed once they are set.
To achieve what you desire, you can use a StringBuilder
StringBuilder someString = new StringBuilder("someString");
someString[4] = 'g';
Update
Why use a string
, instead of a StringBuilder
? For lots of reasons. Here are some I can think of:
- Accessing the value of a string is faster.
- strings can be interned (this doesn't always happen), so that if you create a string with the same value then no extra memory is used.
- strings are immutable, so they work better in hash based collections and they are inherently thread safe.
Replacing a char at a given index in string?
Use a StringBuilder
:
StringBuilder sb = new StringBuilder(theString);
sb[index] = newChar;
theString = sb.ToString();
How can I get a character in a string by index?
string s = "hello";
char c = s[1];
// now c == 'e'
See also Substring
, to return more than one character.
Getting character at a particular index in a string c#
string myString = "HelloWorld";
char myChar = myString[index];
What is the default way to change a character at a certain index in a C# string?
String
is imutable. You can use StringBuilder
to mutate a string:
var s = "abc";
var sb = new StringBuilder(s);
sb[1] = 'd';
s = sb.ToString();
Assign new value to a string index
Every time you go through this for loop, it will evaluate true if the string contains @
, #
, ^
, *
and +
anywhere in the string. So if your string is missing any of these symbols, your if
statement will evaluate to false
and nothing will happen.
Luckily you can simplify this pretty easily. One way you can do this is to convert your string
to a char[]
array and break your logic into multiple if
-else
statements, or a single switch
statement, for example:
public static string Decipher (string code)
{
char[] codeArray = code.ToCharArray(); // convert your code string to a char[] array
for (int i = 0; i < codeArray.Length; i++)
{
switch (codeArray[i]) // Get the char at position i in the array
{
case '@': // if the character at i is '@'
codeArray[i] = 'a'; // Change the character at i to 'a'
break; // break out of the switch statement - we don't need to evaluate anything else
case '#': // if the character at i is '#'
codeArray[i] = 'e'; // Change the character at i to 'e'
break; // break out of the switch statement - we don't need to evaluate anything else
// repeat for everything else you need to replace!
}
}
return new String(codeArray); // Once you're all done, create a string from your deciphered array and return it
}
Replace character at specific index in Liststring, but indexer is read only
You cannot modify C# strings directly, because they are immutable. You can convert strings to char[]
, modify it, then make a string
again, and write it to file:
File.WriteAllLines(
@"c:\newfile.txt"
, File.ReadAllLines(@"C:\...").Select((s, index) => {
if (index % 2 = 0) {
return s; // Even strings do not change
}
var chars = s.ToCharArray();
chars[483] = '0';
return new string(chars);
})
);
How to change 1 char in the string?
I found a solution in unsafe context:
string str = "gg"; char c = 'H'; int index = 1;
fixed (char* arr = str) arr[index] = 'H';
Console.WriteLine(str);
It's so simple.
And in safe context:
string str = "gg"; char c = 'H'; int index = 1;
GCHandle handle = GCHandle.Alloc(str, GCHandleType.Pinned);
IntPtr arrAddress = handle.AddrOfPinnedObject();
Marshal.WriteInt16(arrAddress + index * sizeof(char), c);
handle.Free();
Console.WriteLine(str);
Replace single chars in string at position x
String is immutable class, so use StringBuilder instead:
...
StringBuilder temp = new StringBuilder(lblWord.Text);
temp[i] = letter; // <- It is possible here
lblWord.Text = temp.ToString();
...
Insert value into a string at a certain position?
You can't modify strings; they're immutable. You can do this instead:
txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);
Related Topics
How to Tell If My Process Is Running as Administrator
How to Print PDF on Default Network Printer Using Ghostscript (Gswin32C.Exe) Shell Command
Generate Ef Orderby Expression by String
Exporting Datagridview to CSV File
What's the Difference Between Double Quotes and Single Quote in C#
How to Get the Subscribers of an Event
Determine Number of Pages in a PDF File
"The Linq Expression Node Type 'Invoke' Is Not Supported in Linq to Entities" - Stumped!
..The Underlying Connection Was Closed: an Unexpected Error Occurred on a Receive
C# Getting Value of Params Using Reflection
How to Set Read Permission on the Private Key File of X.509 Certificate from .Net
How to Split an Ienumerable<String> into Groups of Ienumerable<String>
C# - Making All Derived Classes Call the Base Class Constructor
Get the Name of a Method Using an Expression
Giving Application Elevated Uac
Cannot Convert Type 'Task<Derived>' to 'Task<Interface>'
Sorting an Array of Folder Names Like Windows Explorer (Numerically and Alphabetically) - Vb.Net
What's Difference Between Environment.Exit() and Application.Shutdown()