-1

I'm having trouble trying to split a message I receive. I am splitting it because I need to assign the name part to a name variable and the information part to the information variable. The message I receive is:

PUT /Person\r\n\r\nis in this building\r\n

"Person" is the name and "is in this building" is the location. this is also a 0.9 protocol.

For another message I managed to do it, this was the code I did:

string tmp1 = null;
temp = line.Remove(0, 6); //removes first part to bring name to beginning
line = temp.Replace(" HTTP/1.0\\r\\nContent-Length", ""); //removes quote from message
string[] tmp = temp.Split(':'); //Splits name and location apart
name = tmp[0];
tmp1 = tmp[1];                  //Name and location set
location = tmp1.Remove(0, 11);  //further trimming to location
tmp1 = location;          
amount = tmp1.Count();
location = tmp1.Remove(amount - 4);  //Location set

Above is an example of something that I have done, it receives a message similar to the quote I provided and basically splits it apart somewhere and gets rid of the things like "\r\n" or protocol information that I don't want. However, It is also at risk if a message comes in with information including ":" as it would always split. so I am at a fault there.

I am unsure what I could do to extract the information I want as the incoming data in the message could be of any length. So it's fairly difficult. I also thought of splitting it into arguments by "" but it does not let me since it's part of things like "\r\n" etc.

What could I do? Hope what I provided is useful.

Closest thing I have got to splitting it properly is doing

liness = line.Split('\\');

but it splits it into more than 2 or 3 arguments because I am not removing the "r" and "n" from "\r\n" either.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

-1

if the string really contains the actual characters "\r\n" etc first thing I would do is fix that because that's plain nasty. Then use this q&a to split it up

How can I turn a multi-line string into an array where each element is a line of said string?

    var str = "PUT /Person\\r\\n\\r\\nis in this building\\r\\n";
    var clean = str.Replace("\\r\\n", System.Environment.NewLine);
    string[] splitted = clean.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
    foreach (string line in splitted) {
        Console.WriteLine(line);
    }
pm100
  • 48,078
  • 23
  • 82
  • 145
  • It does it. and Yes, it is nasty. What is happening is, a message is sent from a server with an argument in between "". so it gets sent to me like so as "POST /PERSON \r\rn\r\n is in building" and I am reading this message by: string message = null; message += sr.readLine(); //Incoming message being analysed. If that helps – randomUser1212421 Mar 06 '22 at 01:32