Korsun Pavel
Korsun Pavel

Reputation: 19

How to add a unique string before and after a character in a string

I have a string "AAAA", and I need to add certain lines before each character in this string. For example, given

string original = "AAAA". 
string firstStringBeforeChar = "B"
string firststringAfterChar = "C"

and after the conversion, I want to get a string:

string converted = "BACAAA"

For each index, the original string will have its own stringBeforeChar and stringAfterChar. The final output should be like this:

string converted = "BACBACBACBAC"

Where B and C are unique strings for each character in the string original. How do I do this?

Upvotes: 0

Views: 220

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

If you want to add before and after character you can try Linq: for each character c we decide what to put into result and then Concat all our decisions into the finla string.

If you want to add before certain char, here it is 'A':

using System.Linq;

...

var result = string.Concat(original 
  .Select(c => c == 'A'
             ? $"{firstStringBeforeChar}{c}{firststringAfterChar}"
             : $"{c}"));

If you want to add before / after any char, drop the condition:

using System.Linq;

...

var result = string.Concat(original 
  .Select(c => $"{firstStringBeforeChar}{c}{firststringAfterChar}"));

Upvotes: 0

ocean
ocean

Reputation: 375

You can use a loop to iterate through each character in the original string, and use the StringBuilder class to append the appropriate strings before and after each character

Example:

using System.Text;

string original = "AAAA";
string[] stringBeforeChar = {"B", "D", "E", "F"};
string[] stringAfterChar = {"C", "G", "H", "I"};

StringBuilder sb = new StringBuilder();

for (int i = 0; i < original.Length; i++)
{
    sb.Append(stringBeforeChar[i]);
    sb.Append(original[i]);
    sb.Append(stringAfterChar[i]);
}

string converted = sb.ToString();
Console.WriteLine(converted);
Console.WriteLine(converted);

Output:

BACDAGEAHFAI

Upvotes: 2

Tomsen
Tomsen

Reputation: 331

You can do this in a single line of code.

string converted = original.Replace(original[0].ToString(), $"{firstStringBeforeChar}{original[0]}{firststringAfterChar}");

Upvotes: 1

Yash Dhanwantri
Yash Dhanwantri

Reputation: 83

You can do like this, if that's what you are asking:

    string original = "AAAA";
    string firstStringBeforeCharacter = "B";
    string firstStringAfterCharacter = "C";
    var result = new StringBuilder();
    foreach(var c in original)
    {
        result.Append($"{firstStringBeforeCharacter}{c}{firstStringAfterCharacter}");
    }

    Console.WriteLine(result.ToString());

Upvotes: 0

Related Questions