Home > Net >  Replace certain chars with strings on a string, from a list of strings [C#]
Replace certain chars with strings on a string, from a list of strings [C#]

Time:05-10

I'm trying to replace the 'x's with some values from a List<string>.

My initial string looks like this,

string initalText = "x-x-x Sel. Local. Area § x";

I'm reading my initial text from a csv, therefore I cannot change it.

My list of strings looks like this.
enter image description here

I want the final output as,

"5-100-101 Sel. Local. Area § 1.1"

CodePudding user response:

If the strings all look like your example, use 4 regex replaces:

Replace with "5":

^x

Replace with "100":

(?<=x-)x(?=-x)

Replace with "101":

(?<=x-x-)x

Replace with "1.1":

(?<=Area § )x

CodePudding user response:

Given you always know the length of your text list then you can do something like this:

using System;  
using System.Collections.Generic;  

public class Example
{
    public static void Main(string[] args)
    {
        var text = new List<string>();
        
        text.Add("5");
        text.Add("100");
        text.Add("101");
        text.Add("1.1");
        
        string finalText = $"{text[0]}-{text[1]}-{text[2]} Sel. Local. Area § {text[3]}";
        Console.WriteLine(finalText);
    }
}

CodePudding user response:

If the amount of items to replace isn't known or may change, you want a method to manually replace and insert.

string SubstringFormat(string initial, string substring, string[] replacements)
{
    int replacementIndex = 0;
    int index = 0;
    string mutatedString = initial;

    while (index < mutatedString.Length)
    {
        if (replacementIndex >= replacements.Length)
            break;
    
        index = mutatedString.IndexOf(substring, index);

        if (index == -1)
            break;

        mutatedString = mutatedString
            .Remove(index, substring.Length)
            .Insert(index, replacements[replacementIndex]);

        index  = replacements[replacementIndex  ].Length;
    }

    return mutatedString;
}

CodePudding user response:

You can use Format String, consider the following function:

private string GetFormattedString(List<string> text)
    {
        return String.Format("{0}-{1}-{2} Sel. Local. Area § {3}",text[0], text[1], text[2], text[3]);
    }
  • Related