簡體   English   中英

如何將上標字符轉換為 C# 字符串中的普通文本

[英]How to convert superscript characters to normal text in C# string

我有帶有數學表達式的字符串,例如2⁻¹² + 3³ / 4⁽³⁻¹⁾

我想將這些字符串轉換為2^-12 + 3^3 / 4^(3-1)的形式。

到目前為止,我可以提取上標數字並添加^

下面的代碼小提琴: 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 的集合來替換它們,它接受 arrays 作為搜索和替換參數?

額外的問題,如何用普通文本替換各種上標字符並返回上標?

你只需要一個字典到 map 這些值,然后你可以使用 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()) + "]+)"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM