星期三, 9月 16, 2015

[C#] 擷取字串內容

論壇問題,要截取特定字串內指定目標的內容

完全不懂正則表示式,用 indexof() 搭配 substring() 來練習
namespace CatchTargetString
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> source = new List<strng>()
            {
                "yyhhhh=rrtrygfhgfhjgfj; vmjhdkadklajd=gjfxghytuytddxfhgf; 546444=jkdhghffkjdk;  kljjkk=jstrygfhgfhkjs;" ,
                "vmjhdkadklajd=gjfxghgfhgfhgf; 546444=jkjjkjdk; kljjkk=jskljkjs; yyhhhh=rrrgfjytyjjghjgfj;" ,
                "vmjhdkadklajd=gjfxtrytrytryhgf; 546444=jkjjdhgtytryk; yyhhhh=rrhhgjytuytgfj; kljjkk=jskyuytuytjs;"
            };

            string
                targetStart = "yyhhhh=",
                targetEnd = ";",
                data;
             int 
                indexStart, 
                indexEnd ,
                targetStartLength = targetStart.Length;

             List<string> result = new List<string>();

             foreach (string item in source)
             {
                 indexStart = item.IndexOf(targetStart);
                 if (indexStart == -1) continue;
                 indexEnd = item.IndexOf(targetEnd, indexStart);
                 if (indexEnd == -1) continue;

                 data = item.Substring(indexStart + targetStartLength, indexEnd - indexStart - targetStartLength);
                 result.Add(data);
             }

             dump(result);
         }

         public static void dump(List<string> source)
         {
             foreach (string item in source)
             {
                 Console.WriteLine(item);
             }
         }
    }
}
[C#] 擷取字串內容
該找個時間學習正則表示式了,>.<

沒有留言:

張貼留言