misctp asdas
misctp asdas

Reputation: 1023

Extracting values from a string in C#

I have the following string which i would like to retrieve some values from:

============================
Control 127232:
map #;-
============================
Control 127235:
map $;NULL
============================
Control 127236:

I want to take only the Control . Hence is there a way to retrieve from that string above into an array containing like [127232, 127235, 127236]?

Upvotes: 0

Views: 518

Answers (4)

Actel
Actel

Reputation: 21

Off the top of my head try this (it's quick and dirty), assuming the text you want to search is in the variable 'text':

        List<string> numbers = System.Text.RegularExpressions.Regex.Split(text, "[^\\d+]").ToList();
        numbers.RemoveAll(item => item == "");   

The first line splits out all the numbers into separate items in a list, it also splits out lots of empty strings, the second line removes the empty strings leaving you with a list of the three numbers. if you want to convert that back to an array just add the following line to the end:

        var numberArray = numbers.ToArray();

Upvotes: 1

Tadeusz
Tadeusz

Reputation: 6913

Yes, the way exists. I can't recall a simple way for It, but string is to be parsed for extracting this values. Algorithm of it is next:

  1. Find a word "Control" in string and its end
  2. Find a group of digits after the word
  3. Extract number by int.parse or TryParse
  4. If not the end of the string - goto to step one

realizing of this algorithm is almost primitive..)

This is simplest implementation (your string is str):

    int i, number, index = 0;        
    while ((index = str.IndexOf(':', index)) != -1)
    {
        i = index - 1;
        while (i >= 0 && char.IsDigit(str[i])) i--;
        if (++i < index)
        {
            number = int.Parse(str.Substring(i, index - i));
            Console.WriteLine("Number: " + number);
        }
        index ++;
    }

Using LINQ for such a little operation is doubtful.

Upvotes: 0

Marco
Marco

Reputation: 57593

try this (assuming your string is named s and each line is made with \n):

List<string> ret = new List<string>();
foreach (string t in s.Split('\n').Where(p => p.StartsWith("Control")))
    ret.Add(t.Replace("Control ", "").Replace(":", ""));

ret.Add(...) part is not elegant, but works...

EDITED:
If you want an array use string[] arr = ret.ToArray();

SYNOPSYS:
I see you're really a newbie, so I try to explain:

  • s.Split('\n') creates a string[] (every line in your string)
  • .Where(...) part extracts from the array only strings starting with Control
  • foreach part navigates through returned array taking one string at a time
  • t.Replace(..) cuts unwanted string out
  • ret.Add(...) finally adds searched items into returning list

Upvotes: 2

Jamiec
Jamiec

Reputation: 136239

One way of achieving this is with regular expressions, which does introduce some complexity but will give the answer you want with a little LINQ for good measure.

Start with a regular expression to capture, within a group, the data you want:

var regex = new Regex(@"Control\s+(\d+):");

This will look for the literal string "Control" followed by one or more whitespace characters, followed by one or more numbers (within a capture group) followed by a literal string ":".

Then capture matches from your input using the regular expression defined above:

var matches = regex.Matches(inputString);

Then, using a bit of LINQ you can turn this to an array

var arr = matches.OfType<Match>()
                 .Select(m => long.Parse(m.Groups[1].Value))
                 .ToArray();

now arr is an array of long's containing just the numbers.

Live example here: http://rextester.com/rundotnet?code=ZCMH97137

Upvotes: 3

Related Questions