N
N
Napseg2012-05-21 23:26:16
.NET
Napseg, 2012-05-21 23:26:16

Analog of php function strtr in .Net

Can you please tell me how to perform such a function in .Net?

For example

$a=array("o" => "l", "l" => "o");
$b=strtr("ololo",$a);


As I understand it, a simple pass through the array will not work, because otherwise it turns out
1) lllll
2) ooooo
And it should turn out lolol

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
catlion, 2012-05-22
@Napseg

using System;
using System.Text;
using System.Collections.Generic;

class Program
{
  public static void Main(string[] args)
  {
    var repl = new Dictionary<char, char> { {'o', 'l'}, {'l','o'} };
    var src = "ololo";
    Console.WriteLine("Source string: " + src + "; changed string: " + src.Strtr(repl));
    Console.ReadKey();
  }
}

public static class StringExt
{
  public static string Strtr(this string src, Dictionary<char, char> replacePairs) {
    var sb = new StringBuilder();
    foreach (char c in src) {
      if(replacePairs.ContainsKey(c)) {
        sb.Append(replacePairs[c]);
      } else {
        sb.Append(c);
      }
    }
    
    return sb.ToString();
  }
}

I
Iliapan, 2012-05-21
@Iliapan

There are several options, the most useful for you is through regexps. Deal with them and then it will come in handy. Regex.Replace and further as you fantasize.

E
eforce, 2012-05-22
@eforce

For starters, can we take this as a basis Equalvilent method in c# for strtr functon in php?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question