'Splitting a string into two new strings

I'm trying to split a string into two and store it into two new strings named username and location.

The incoming string contains

PUT /605226\r\n\r\nis being tested\r\n

I would like to extract 605226 as the username and is being tested as the location.

What would be the best way to do this?

Here is the code I want to implement it in, I cant use string arrays btw, Ive tried it/

else if (message.StartsWith("PUT /"))
{
  message.Replace("PUT /", "");
  
  username = "";
  location = "";
  
  if (UID.ContainsKey(username.Trim()))
  {
    sw.WriteLine(username);
    UID[username] = location;
    sw.WriteLine($"HTTP/0.9 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  }
  else
  {
    sw.WriteLine(username);
    UID.Add(username, location);
    sw.WriteLine($"HTTP/0.9 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  }
  sw.Flush();
}


Solution 1:[1]

Why not use Regex?

Regex rx = new Regex(@"\/(\d*)\r\n\r\n(.*)\r\n");
MatchCollection matches = rx.Matches(message);
    
if (matches.Count < 1) {
    // not matched, can't extract username or location
}
        
string username = matches[0].Groups[1].Value;
string location = matches[0].Groups[2].Value;

// From here on, username will be '605226' and location 'is being tested'

This assumes the following:

  • username will be a number and will go after a /.
  • \r\n\r\n separates the username from the location.
  • message ends with \r\n.

Solution 2:[2]

How about…

else if (message.StartsWith("PUT /"))
    {

    username = message.Split('/')[1].Split('\r')[0];

    location = message.Split('\n')[2].Split('\r')[0];

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 moonstar-x
Solution 2