Languages
[Edit]
EN

C# / .NET - add character to string

0 points
Created by:
Dharman
518

In this article, we would like to show you how to add character to string in C#.

Quick solution:

string text = "ABC";
char character = 'x';
string result = text + character;

Console.WriteLine(result); // ABCDx

or:

string text = "ABCD";
char character = 'x';
int index = 1;

string result = text.Insert(index, character.ToString());

Console.WriteLine(result); // AxBCD

 

1. Practical example using + operator

In this example, we add a character at the end of the text string using + operator.

using System;

public class TestClass
{
    public static void Main()
    {
        string text = "ABC";
        char character = 'x';
        string result = text + character;

        Console.WriteLine(result);
    }
}

Output:

ABCDx

2. Using String.Insert() method

In this example, we use Insert() method to add a character to the string at specific position (index).

using System;

public class TestClass
{
    public static void Main()
    {
        string text = "ABCD";
        char character = 'x';
        int index = 1;

        string result = text.Insert(index, character.ToString());

        Console.WriteLine(result);
    }
}

Output:

AxBCD

References

  1. String.Insert(Int32, String) Method (System) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join