How to Convert Persian Digits in variable to English Digits Using Culture?

后端 未结 15 2134
终归单人心
终归单人心 2021-02-02 07:10

I want to change persian numbers which are saved in variable like this :

string Value=\"۱۰۳۶۷۵۱\"; 

to

string Value=\"1036751\"         


        
15条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 07:43

    I suggest two approaches to handle this issue(I Create an extension method for each of them):

    1.foreach and replace

    public static class MyExtensions
    {
         public static string PersianToEnglish(this string persianStr)
         {
                Dictionary LettersDictionary = new Dictionary
                {
                    ['۰'] = '0',['۱'] = '1',['۲'] = '2',['۳'] = '3',['۴'] = '4',['۵'] = '5',['۶'] = '6',['۷'] = '7',['۸'] = '8',['۹'] = '9'
                };
                foreach (var item in persianStr)
                {
                    persianStr = persianStr.Replace(item, LettersDictionary[item]);
                }
                return persianStr;
         }
    }
    

    2.Dictionary.Aggregate

    public static class MyExtensions
    {
          public static string PersianToEnglish(this string persianStr)
          {
                Dictionary LettersDictionary = new Dictionary
                {
                    ["۰"] = "0",["۱"] = "1",["۲"] = "2",["۳"] = "3",["۴"] = "4",["۵"] = "5",["۶"] = "6",["۷"] = "7",["۸"] = "8",["۹"] = "9"
                };
                return LettersDictionary.Aggregate(persianStr, (current, item) =>
                             current.Replace(item.Key, item.Value));
          }
    }
    

    More info about Dictionary.Aggregate: Microsoft

    Usage:

    string result = "۱۰۳۶۷۵۱".PersianToEnglish();
    

提交回复
热议问题