簡體   English   中英

檢查C#中某個字符后面是否有另一個字符

[英]check if a certain character is followed by another character in C#

我的string format = #,##,0.00,,我需要計算其中有多少個逗號,但是在上述示例中,與我唯一相關的逗號是后兩個。

我想檢查逗號后面是否是"#""0"

這樣的解決方案會起作用嗎?

int count = 0
for (int i = format.IndexOf(','); i > -1; i = format.IndexOf(',', i + 1))
{
    // for loop end when i=-1 (',' not found)
       // if next character is # or 0 don't count
       // else count
}

如果要計算逗號后跟“#”或“ 0”的逗號,無論它們位於文本的何處(開始,結束),都可以執行以下操作:

Regex.Matches("#,##,0.00,,#,##,0.00,,", ",(?![#0])").Count

返回三。 請注意,第三個逗號后面沒有#或0。如果只希望逗號在字符串末尾匹配,則:

Regex.Matches("#,##,0.00,,#,##,0.00,,", ",(?![#0]),*$").Count

返回兩個。

    private int GetCount()
    {
        string format = "#,##,0.00,,";

        int count = 0;
        for (int i = 0; i < format.Length; i++)
        {
            //if current char is not ',' skip it
            if (!format[i].Equals(','))
            {
                continue;
            }

            //if current char is ',' and its last in string => count++ because no '#' or '0' folows it
            if ((i + 1) == format.Length)
            {
                count++;
                break;
            }

            //if '0' or '#' folows current char, skip current char
            if (format[i + 1].Equals('#')
                || format[i + 1].Equals('0'))
            {
                continue;
            }
            //next char is not '0' or '#' => count++
            count++;
        }
        return count;
    }

您可以嘗試以下方法:

  string format = @"#,##,0.00,,";
  string[] arrStr = format.Split(',');
  int count = 0;

  for(int i = 1; i < arrStr.length - 1; i++) 
  {
       string s = arrStr[i];
       //ignore string starting with # or 0 
       if (!s.StartsWith("#") && !s.StartsWith("0")) 
       {
            count++;
       }
   }

這是使用上述代碼的不同輸入和輸出:

 //string format = @"#,##,0.00,,";  
 //Commas Count = 2

 //string format = @"a,a,#,0,a,,";  
 //Commas Count = 4

 //string format = @",,";  
 //Commas Count = 2

 //string format = @",";  
 //Commas Count = 1

 //string format = @",#";  
 //Commas Count = 0

使用正則表達式。 下面的模式僅解決您提到的“最后一個逗號”方案。

string format = "#,##,0.00,,";

string pattern = @"^#,##,\d\.\d\d(?<LastCommas>,+)$";

var myRegex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture);

Match match = myRegex.Match(format);

GroupCollection capturedGroups = match.Groups;

// This will get you the number of commas
int count = capturedGroups["LastCommas"].Value.Length;

如果“最后一個逗號”是可選的(即可以有零個或多個),請用以下內容替換上面的pattern

string pattern = @"^#,##,\d\.\d\d(?<LastCommas>,*)$";
    public static int CountDelimiter(string data)
    {
        var count = 0;
        var previous = char.MinValue;
        foreach (var c in data)
        {
            if (previous != '#' && preivous !='0' && c == ',')
                count++;
            previous = c;
        }
        return count;
    }

或者,如果您希望使用單命令樣式,則可以執行以下操作:

    public static int CountDelimiter(string data)
    {
        return data.Where((x, xi) => x == ',' && 
        (xi == 0 || (xi > 0 && data[xi - 1] != '0' && data[xi - 1] != '#'))).Count();
    }
string string1 = "#,##,$,$%%$,0,^^^,,";

char[] a = new char[1]
{
    ','
};

string[] strArray = string1.Split(a);

foreach (string s in strArray)
        {
            if (s.StartsWith("0") || s.StartsWith("#") || s.StartsWith(",") || s == string.Empty)
            {
                count++;
            }
        }

在這里,當有兩個逗號時,循環將檢查string.Empty

我不確定您要做什么,但可能是這樣的:

static int X(string str)
{
    int endPos = str.Length - 1;
    int count = 0;

    for (int pos = 0; pos <= endPos; pos++)
    {
        if (str[pos] == ',')
        {
            if (pos < endPos)
            {
                char next = str[pos + 1];

                if (next == '#' || next == '0')
                {
                    pos++;

                    continue;
                }
            }

            count++;
        }
    }

    return count;
}

我沒有對此進行測試,但是它可以編譯:

public static int GetModifiedCommaCount(string searchString)
{
    int result = 0;
    int lastIndex = searchString.Length - 1;

    // start looping at our first match to save time
    for (int i = searchString.IndexOf(','); i <= lastIndex && i > 0; i++)
    {
        if (searchString[i] == ',' && (i >= lastIndex || (searchString[i + 1] != '0' && searchString[i + 1] != '#')))
        {
            result++;
        }
    }

    return result;
}

暫無
暫無

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

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