gpt4 book ai didi

c# - 如何在C#字符串中将上标字符转换为普通文本

转载 作者:行者123 更新时间:2023-12-04 10:12:31 25 4
gpt4 key购买 nike

我有带有数学表达式的字符串,例如 2⁻¹² + 3³ / 4⁽³⁻¹⁾ .
我想将这些字符串转换为 2^-12 + 3^3 / 4^(3-1) 的形式.
到目前为止我得到的是我可以提取上标数字并添加 ^ .
下面的代码 fiddle :https://dotnetfiddle.net/1G9ewP

using System;
using System.Text.RegularExpressions;

public class Program
{
private static string ConvertSuperscriptToText(Match m){
string res = m.Groups[1].Value;

res = "^" + res;
return res;
}
public static void Main()
{
string expression = "2⁻¹² + 3³ / 4⁽³⁻¹⁾";
string desiredResult = "2^-12 + 3^3 / 4^(3-1)";

string supChars = "([¹²³⁴⁵⁶⁷⁸⁹⁰⁺⁻⁽⁾]+)";
string result = Regex.Replace(expression, supChars, ConvertSuperscriptToText);

Console.WriteLine(result); // Currently prints 2^⁻¹² + 3^³ / 4^⁽³⁻¹⁾
Console.WriteLine(result == desiredResult); // Currently prints false
}
}
如何替换上标字符而不一一替换它们?
如果我必须一个一个替换它们,我如何使用类似于 PHP 的 str_replace 的集合来替换它们,该集合接受数组作为搜索和替换参数?
奖金问题,如何将各种上标字符替换为普通文本并返回上标?

最佳答案

您只需要一个字典来映射这些值,然后您就可以使用 Linq 来转换它们并从中创建一个新字符串。

private static Dictionary<char, char> scriptMapping = new Dictionary<char, char>()
{
['¹'] = '1',
['²'] = '2',
['³'] = '3',
['⁴'] = '4',
['⁵'] = '5',
['⁶'] = '6',
['⁷'] = '7',
['⁸'] = '8',
['⁹'] = '9',
['⁰'] = '0',
['⁺'] = '+',
['⁻'] = '-',
['⁽'] = '(',
['⁾'] = ')',
};

private static string ConvertSuperscriptToText(Match m){
string res = m.Groups[1].Value;

res = "^" + new string(res.Select(c => scriptMapping[c]).ToArray());
return res;
}

您还可以从字典中创建正则表达式,因此只有一个地方可以添加新的下标。
string supChars = "([" + new string(scriptMapping.Keys.ToArray()) + "]+)"

关于c# - 如何在C#字符串中将上标字符转换为普通文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61260528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com