1

Let say I have a string "ABCDEFGH"and I would like to add a char into this string such as (adding Z to the fourth column);

ABCZDEFGH

How can I do this efficiently instead of changing string into char, moving all chars to the new column, and adding the char later?

5 Answers 5

8

You can use the string.Insert method.

string test = "ABCDEFGH";
test = test.Insert(3, "Z");

Have a look at the docs for more information.

Sign up to request clarification or add additional context in comments.

Comments

2

You could try:

    string str = "ABCDEFGH";

    str = str.Insert(3, "Z");

Comments

2

Why not just Insert:

  string source = "ABCDEFGH";
  char item = 'Z';

  string result = source.Insert(3, item.ToString());

Comments

1

Use string.Insert:

var start = "ABCDEFGH";
var result = start.Insert(3, "Z");

Note that indexes are 0 based.

Comments

0

if you don't know the index you can do it like this

result = test.Insert(test.IndexOf("C"), "Z");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.