esat akpo
esat akpo

Reputation: 45

How to use string literals with a string that has already been assigned C#

This is my string

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

In order to find n1 in this string I have to do this:

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

But what if I declared my string like this as its content came from a text box:

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

How would I then find n1 in the same scenario as the example above as the code below does not work.

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

Upvotes: 0

Views: 54

Answers (2)

Alexander Petrov
Alexander Petrov

Reputation: 14231

In C# the @ symbol using for verbatim strings. Only when writing literals.

No need to apply it to variables. Just write:

string test = this.textbox.Text;

Please note that the ToString() call is not required.

Upvotes: 0

jdweng
jdweng

Reputation: 34421

Use Regex

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();
        }
    }
}

Upvotes: 1

Related Questions