Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string occurrences with list entries

Tags:

string

c#

I've been wrapping my head around this to find an "elegant" solution but I'm not quite satisfied with it.

Possible input strings:

foo () bar ()

() bar

foo

()()foo () bar

There can be "unlimited" brackets and optional, non-bracket text inbetween the brackets. The content of these empty brackets are supposed to filled with data taking from a List<string> in the order of the list entries. If there no entries or not sufficient entries the brackets are untouched.

Possible string replacements:

foo () bar () replaced with x, y will result in foo (x) bar (y)

foo () bar () replaced with x will result in foo (x) bar ()

foo () bar () replaced with x, y, z will result in foo (x) bar (y)

I hope you get the idea.

Solutions: The solutions I had so far are fiddling around with indexes and a lot special logic to handle the different cases.

I wondered if there is a more elegant solution with, for example regex. Maybe I'm too close at the problem right now and there is a simple solution :-)

Here is an approach I'm not really happy about (readability / easy to understand):

  var guiIdentifierIndex = 0;
  var guiIdentifierList = new List<string>{"x", "y", "z", "x", "y"};

  var sourcePathItem = "foo ()";
  string targetString = "";
  var splittedPath = sourcePathItem.Split(new string[] { BRACKETS }, StringSplitOptions.None);
  for (int index = 0; index < splittedPath.Length; index++)
  {
    var subPath = splittedPath[index];
    var guiIdentifier = string.Empty;
    if (guiIdentifierIndex < guiIdentifierList.Count)
    {
      guiIdentifier = guiIdentifierList[guiIdentifierIndex];
      guiIdentifierIndex++;
    }
    targetString += subPath;
    if (index < splittedPath.Length - 1)
      targetString += string.Format("({0})", guiIdentifier);
  }

http://volatileread.com/utilitylibrary/snippetcompiler?id=22718

like image 443
DerApe Avatar asked Mar 14 '26 04:03

DerApe


1 Answers

You can use regular expressions, e.g.

  String source = "foo () bar ()";

  var guiIdentifierList = new List<String> { 
    "x", "y", "z", "x", "y" };

  int guiIdentifierIndex = 0; 

  // result == "foo (x) bar (y)"
  String result = Regex.Replace(source, @"\(\)", (MatchEvaluator) (
    (match) => "(" + (guiIdentifierIndex < guiIdentifierList.Count 
                      ? guiIdentifierList[guiIdentifierIndex++] 
                      : "") + ")"
  ));
like image 183
Dmitry Bychenko Avatar answered Mar 16 '26 16:03

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!