星期一, 6月 16, 2014

[C#] 字串中特定字串出現次數

MVA Twenty C# Questions Explained - [6 How would you count the occurrences of a string within a string?]
  • 利用長度判斷
處理邏輯可以參考這篇文章 [SQL] 字串中特定字串出現次數,只是換成 C# 撰寫
namespace StringCount
{
    class Program
    {
        static void Main(string[] args)
        {
            string strData = "Hello, how are youyou you you you, you you yy?";
            string goal = "you";
            string strReplace = strData.Replace(goal, "");
            int times = (strData.Length - strReplace.Length) / goal.Length ;
            string message = string.Format("字串 {0} 在字串 {1} 中,出現 {2} 次", goal, strData, times);
            Console.WriteLine(message);
        }
    }
}

[C#] 字串中特定字串出現次數-1

  • MVA 範例說明
namespace StringCount
{
    class Program
    {
        static void Main(string[] args)
        {
            string test = "Hello, how are youyou you you you, you you yy?";
            int wordCount = 0;
            int charCount = 0;

            // 正則表示式作法
            foreach (Match m in Regex.Matches(test, "you"))
            {
                wordCount++;
            }
            
            // 此作法只適用單一字元
            foreach (char value in test)
            {
                if (value == 'y')
                {
                    charCount++;
                }
            }

            Console.WriteLine("Word count: {0}", wordCount);
            Console.WriteLine("Character count: {0}", charCount);
        }
    }
}
[C#] 字串中特定字串出現次數-2

沒有留言:

張貼留言