0

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();
4
  • You do realize that in your first sting "\n" is one character, so there is no "n1" there. So what exactly are you looking for? a newline followed by a 1? Commented Apr 29, 2016 at 12:24
  • yes thats the reason i use the @ to change it to \\ and n1. so can you help me or not Commented Apr 29, 2016 at 12:26
  • I'm not clear about what your asking. Are you typing in newlines into the text box or are you typing in a backslash followed by an n? Commented Apr 29, 2016 at 12:27
  • @ is for literal strings. If you type \n in a TextBox, it won't be a newline character, but \ and n. (Why don't you try it out and see what the result is?) @this means something totally different which has nothing to do with strings. Commented Apr 29, 2016 at 12:27

2 Answers 2

1

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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.