How to get a word in string C#

Given :

string command = "<CP1><SSA1>";
string command_2 = "<CP1><MPS>";

How can I get the word "CP1" and "1" from 'SSA1' in command and for command_2 is "CP1" and "MPS" then set to another variables?

I already search the similar question but still not found the best answer.

Edited :

For command variable, I want get 'CP1' from CP1 and '1' from SSA1. And for command_2 variable I want get 'CP1' from CP1 and 'MPS' from MPS.

Answers


You just need to get strings between angled brackets.. then you just replace "SSA" with "" and you have all the words you wanted !!!

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

class Program
{
    static void Main()
    {
        string command = "<CP1><SSA1>";
        string command_2 = "<CP1><MPS>";

        prnt(command);
        prnt(command_2);
            //prnt(command+command_2); //even this will work :)
    }

    private static void prnt(string str)
    {
                List<string> l = ExtractFromString(str,"<",">");
        foreach(string ll in l)
            Console.WriteLine(ll.Replace("SSA",""));
    }

    private static List<string> ExtractFromString(string text, string start, string end)
    {            
        List<string> Matched = new List<string>();
        int index_start = 0, index_end=0;
        bool exit = false;
        while(!exit)
        {
            index_start = text.IndexOf(start);
            index_end = text.IndexOf(end);
            if (index_start != -1 && index_end != -1)
            {
                Matched.Add(text.Substring(index_start + start.Length, index_end - index_start - start.Length));
                text = text.Substring(index_end + end.Length);
            }
            else
                exit = true;
        }
        return Matched;
    }
}
Output:
CP1
1
CP1
MPS

Source of Extract method: Extract all strings between two strings


Need Your Help

Exposing Metadata Exchange for use with svcutil

wcf service metadata svcutil.exe

I am trying to take a very simple (essentially empty/function-less) service I have and generate a proxy with svcutil.exe. Here's my server:

How to explain heap and stack do not grow towards each other

.net stack heap

When I debug these lines of code, I can observe ms/ms2 are instances of value type and they are allocated on stack, and o (boxed MyStruct instance) is reference type and is allocated in managed hea...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.