简体   繁体   中英

c# getting a string within another string

i have a string like this:

 some_string = "A simple demo of SMS text messaging.\r\n+CMGW: 3216\r\n\r\nOK\r\n\"

im coming from vb.net and i need to know in c#, if i know the position of CMGW, how do i get "3216" out of there?

i know that my start should be the position of CMGW + 6, but how do i make it stop as soon as it finds "\\r" ??

again, my end result should be 3216

thank you!

Find the index of \\r from the start of where you're interested in, and use the Substring overload which takes a length :

// Production code: add validation here.
// (Check for each index being -1, meaning "not found")
int cmgwIndex = text.IndexOf("CMGW: ");

// Just a helper variable; makes the code below slightly prettier
int startIndex = cmgwIndex + 6;
int crIndex = text.IndexOf("\r", startIndex);

string middlePart = text.Substring(startIndex, crIndex - startIndex);

If you know the position of 3216 then you can just do the following

string inner = some_string.SubString(positionOfCmgw+6,4);

This code will take the substring of some_string starting at the given position and only taking 4 characters.

If you want to be more general you could do the following

int start = positionOfCmgw+6;
int endIndex = some_string.IndexOf('\r', start);
int length = endIndex - start;
string inner = some_string.SubString(start, length);

One option would be to start from your known index and read characters until you hit a non-numeric value. Not the most robust solution, but it will work if you know your input's always going to look like this (ie, no decimal points or other non-numeric characters within the numeric part of the string).

Something like this:

public static int GetNumberAtIndex(this string text, int index)
{
    if (index < 0 || index >= text.Length)
        throw new ArgumentOutOfRangeException("index");

    var sb = new StringBuilder();

    for (int i = index; i < text.Length; ++i)
    {
        char c = text[i];
        if (!char.IsDigit(c))
            break;

        sb.Append(c);
    }

    if (sb.Length > 0)
        return int.Parse(sb.ToString());
    else
        throw new ArgumentException("Unable to read number at the specified index.");
}

Usage in your case would look like:

string some_string = @"A simple demo of SMS text messaging.\r\n+CMGW: 3216\r\n...";
int index = some_string.IndexOf("CMGW") + 6;
int value = some_string.GetNumberAtIndex(index);

Console.WriteLine(value);

Output:

3216

If you're looking to extract the number portion of 'CMGW: 3216' then a more reliable method would be to use regular expressions. That way you can look for the entire pattern, and not just the header.

 var  some_string = "A simple demo of SMS text messaging.\r\n+CMGW: 3216\r\n\r\nOK\r\n";
 var match = Regex.Match(some_string, @"CMGW\: (?<number>[0-9]+)", RegexOptions.Multiline);
 var number = match.Groups["number"].Value;

More general, if you don't know the start position of CMGW but the structure remains as before.

 String s;
    char[] separators = {'\r'};
    var parts = s.Split(separators);
    parts.Where(part => part.Contains("CMGW")).Single().Reverse().TakeWhile(c => c != ' ').Reverse();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM