string manipulation
programming tutorial
character replacement
coding basics
software development

Changing a character in a string

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Changing one character in a string is a simple task conceptually, but the implementation depends on whether the language treats strings as mutable. In many mainstream languages, strings are immutable, which means you do not modify the original string in place; you build a new string with the changed character.

The Core Idea: Strings Are Often Immutable

In languages such as Python, Java, JavaScript, and C#, strings are immutable. That means this idea is usually wrong:

  • find character at index i
  • overwrite it inside the same string object

Instead, the normal pattern is:

  • take the part before the index
  • insert the replacement character
  • append the rest of the string

That produces a new string value.

Python Example

Python strings are immutable, so slicing is the standard approach:

python
1text = "cat"
2index = 0
3replacement = "b"
4
5new_text = text[:index] + replacement + text[index + 1:]
6print(new_text)  # bat

If you need to make many changes, converting once to a list of characters can be more efficient:

python
1chars = list("hello")
2chars[1] = "a"
3result = "".join(chars)
4
5print(result)  # hallo

This avoids repeated string reconstruction when many edits are required.

JavaScript Example

JavaScript strings are also immutable:

javascript
1const text = "cat";
2const index = 2;
3const replacement = "r";
4
5const result = text.slice(0, index) + replacement + text.slice(index + 1);
6console.log(result); // car

Just like in Python, the original string is unchanged and a new one is returned.

Java Example

In Java, String is immutable, so substring composition is a standard pattern:

java
1String text = "cat";
2int index = 1;
3char replacement = 'u';
4
5String result = text.substring(0, index)
6        + replacement
7        + text.substring(index + 1);
8
9System.out.println(result); // cut

If you are making many modifications, StringBuilder is often a better tool:

java
1StringBuilder builder = new StringBuilder("hello");
2builder.setCharAt(4, 'a');
3
4System.out.println(builder); // hella

This is a good reminder that sometimes the right answer is not “change the string,” but “use a mutable string-like structure.”

C# Example

C# strings are immutable too:

csharp
1string text = "code";
2int index = 0;
3char replacement = 'm';
4
5string result = text.Substring(0, index)
6               + replacement
7               + text.Substring(index + 1);
8
9Console.WriteLine(result); // mode

For multiple edits, converting to a character array can be clearer:

csharp
1char[] chars = "hello".ToCharArray();
2chars[0] = 'y';
3string result = new string(chars);
4
5Console.WriteLine(result); // yello

Validate the Index

Regardless of language, you should validate that the target index is inside the string bounds. A simple defensive helper in Python looks like this:

python
1def replace_char(text, index, replacement):
2    if not 0 <= index < len(text):
3        raise IndexError("index out of range")
4    if len(replacement) != 1:
5        raise ValueError("replacement must be one character")
6    return text[:index] + replacement + text[index + 1:]
7
8print(replace_char("mouse", 0, "h"))

This avoids subtle bugs such as empty replacements or accidental multi-character insertion when the caller meant to replace exactly one character.

When Not to Treat It as a Single-Character Problem

Sometimes the operation is really:

  • replace every occurrence of a character
  • replace a substring
  • perform many edits efficiently

In those cases, language-specific replace functions or mutable builders are usually better than repeating single-index logic.

The key is to match the tool to the real operation instead of forcing everything through one-character replacement code.

Common Pitfalls

  • Assuming strings are mutable and trying to assign directly into them.
  • Forgetting to validate the index and causing out-of-range errors.
  • Allowing a multi-character replacement when the intent was to replace exactly one character.
  • Rebuilding very large strings repeatedly when a mutable buffer would be more efficient.
  • Solving a global replace problem with single-character index logic.

Summary

  • In many languages, changing a character in a string really means creating a new string.
  • Slicing and concatenation are the usual one-off solution.
  • For repeated edits, use a mutable representation such as a list, character array, or string builder.
  • Always validate the target index and replacement size.
  • Choose the operation based on whether you need one replacement, many replacements, or full substring manipulation.

Course illustration
Course illustration

All Rights Reserved.