Click here to Skip to main content
16,005,236 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,


I need to searh specific text from string. My string contains below text
-------------------------
A 0 B 1 C 0
One: 1

A 0 B 2 C 1
Two: 2

A 0 B 3 C 2
Three: 3
-------------------------
I need to searh exact line by passing paramter like, if i pass paramater (0,2,1) then answer return text should Two:2

Can I use regular expression here.

I can also do this with foreach loop, but need to go with regular expression.

Please suggest.

Regards,
YRishi
Posted
Comments
Karthik_Mahalingam 25-Jan-14 14:28pm    
always it will be A x B x C x ??
yrishi 26-Jan-14 2:24am    
Thanks Karthik for your reply. Yes that will be the fix.
Karthik_Mahalingam 26-Jan-14 2:26am    
welcome yrishi :)
Peter Leow 25-Jan-14 14:28pm    
What is the role of A, B, and C here?
yrishi 26-Jan-14 2:25am    
Its just heading for respective lines.

1 solution

You can do without looping also..
if it helpful, you can use this.

C#
using System;
using System.Linq;

namespace oops1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "A 0 B 1 C 0" + "\n" +
                            "One: 1" + "\n" +
                           " A 0 B 2 C 1" + "\n" +
                            "Two: 2" + "\n" +
                            "A 0 B 3 C 2" + "\n" +
                            "Three: 3";

            string output = GetText(input, 0, 1, 0); //output is -> One: 1

            Console.WriteLine(output);
            Console.ReadLine();

        }

        public static string GetText(string input, int a, int b, int c)
        {
            string format = "A {0} B {1} C {2}";
            var array = input.Split('\n').ToList();
            int index = array.IndexOf(string.Format(format, a, b, c)) + 1;
            return array[index];
        }
    }
}
 
Share this answer
 
Comments
BillWoodruff 25-Jan-14 22:11pm    
+5 very creative solution, interesting use of string.Format !
Karthik_Mahalingam 25-Jan-14 22:40pm    
Thanks BillWoodruff :)
yrishi 26-Jan-14 2:26am    
Yes, very creative solution.
Karthik_Mahalingam 26-Jan-14 2:27am    
Thanks yrishi :)
yrishi 26-Jan-14 2:26am    
Thanks a lot Karthik. Will try and let you know

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900