如何将字符串文字与已分配C#的字符串一起使用

时间:2016-04-29 12:22:01

标签: c#

这是我的字符串

string test = "255\r\n\r\n0\r\n\r\n-1\r\n\r\n255\r\n\r\n1\r";

为了在这个字符串中找到n1,我必须这样做:

string test = @"255\r\n\r\n0\r\n\r\n-1\r\n\r\n255\r\n\r\n1\r";

但是如果我将这样的字符串声明为内容来自文本框,那该怎么办:

string test = this.textbox.Text.ToString();

我如何在与上面示例相同的场景中找到n1,因为下面的代码不起作用。

  string test = @this.textbox.Text.ToString();

2 个答案:

答案 0 :(得分:1)

使用正则表达式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;


namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            string test1 = "255\r\n\r\n0\r\n\r\n-1\r\n\r\n255\r\n\r\n1\r";
            string test2 = @"255\r\n\r\n0\r\n\r\n-1\r\n\r\n255\r\n\r\n1\r";

            Console.WriteLine("First String");
            MatchCollection matches = Regex.Matches(test1, @"\d+", RegexOptions.Singleline);
            foreach (Match match in matches)
            {
                Console.WriteLine(match.Value);
            }

            Console.WriteLine("Second String");
            matches = Regex.Matches(test2, @"\d+", RegexOptions.Singleline);
            foreach (Match match in matches)
            {
                Console.WriteLine(match.Value);
            }
            Console.ReadLine();
        }
    }
}

答案 1 :(得分:0)

在C#中,@符号用于逐字字符串。只有在写文字时。

无需将其应用于变量。只需写下:

string test = this.textbox.Text;

请注意,不需要ToString()来电。

相关问题