簡體   English   中英

在特定字符處拆分字符串 (C#)

[英]Split string at particular characters (C#)

我想要做的是拆分一個數組,然后將我拆分的字符放入另一個元素
IE
string text = "1*5+89-43&99"
應該成為
string[] textsplit = ["1","*","5","+","89","-","43","&","99"] (必須是字符串)和我將提供要留在單獨元素中的字符

您可以使用string.IndexOfAny來做到這一點。

只需繼續尋找任何分隔符的下一個索引。 找到分隔符后,將其與最后一個分隔符之間的文本添加到結果中,然后查找下一個分隔符。

string input = "1*1*5+89-43&33";
var separators = new[] { '+', '-', '*', '/', '&' };
var result = new List<string>();

int index;
int lastIndex = 0;
while ((index = input.IndexOfAny(separators, lastIndex)) != -1)
{
    // Add the text before the separator, if there is any
    if (index - lastIndex > 0)
    {
        result.Add(input.Substring(lastIndex, index - lastIndex));
    }
    
    // Add the separator itself
    result.Add(input[index].ToString());

    lastIndex = index + 1;  
}

// Add any text after the last separator
if (lastIndex < input.Length)
{
    result.Add(input.Substring(lastIndex));
}

這是一個基本而幼稚的實現,我相信我們會做你想做的:

public static List<string> SplitExpression(string expression)
{
    var parts = new List<string>();
    
    bool isNumber(char c) => c == '.' || (c >= '0' && c <= '9');
    bool isOperator(char c) => !isNumber(c);

    int index = 0;
    while (index < expression.Length)
    {
        char c = expression[index];
        index++;

        if (isNumber(c))
        {
            int numberIndex = index - 1;
            while (index < expression.Length && isNumber(expression[index]))
                index++;
            parts.Add(expression.Substring(numberIndex, index - numberIndex));
        }
        else
            parts.Add(c.ToString());
    }

    // move unary signs into following number
    index = 0;
    while (index < parts.Count - 1)
    {
        bool isSign = parts[index] == "-" || parts[index] == "+";
        bool isFirstOrFollowingOperator = index == 0 || isOperator(parts[index - 1][0]);
        bool isPriorToNumber = isNumber(parts[index + 1][0]);
        
        if (isSign && isFirstOrFollowingOperator && isPriorToNumber)
        {
            parts[index + 1] = parts[index] + parts[index + 1];
            parts.RemoveAt(index);
        }
        else
            index++;
    }
    return parts;
}

示例輸入: "-1+-2*-10.1*.1"和 output:

-1 
+ 
-2 
* 
-10.1 
* 
.1 

嘗試使用以下代碼片段:

        string text  = "1*1*5+89-43&33";
        List<string> textsplit = new List<string>();
        foreach(var match in Regex.Matches(text, @"([*+/\-)(])|([0-9]+)"))
        {
            textsplit.Add(match.ToString());
        }

結果添加為圖像。

結果會是這樣

暫無
暫無

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

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