Richard
Richard

Reputation: 15862

Having problems stripping white space with C#

I have pasted a code snip below that I have written which reads a line of data from a serial port when there is data in the buffer, However I am printing extra blank lines which I do not want.. Any Idea what I am doing wrong?

static void Port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    int i = 0;
    int end = -1;
    SerialPort Port1 = (SerialPort)sender;
    String GPSMessage = "";

    while (end == -1)
    {
        int GPStoRead = Port1.BytesToRead;
        byte[] GPSbuffer = new byte[GPStoRead];
        Port1.Read(GPSbuffer, 0, GPSbuffer.Length);
        buffer = Utility.CombineArrays(buffer, GPSbuffer);
        for (i = 0; i < buffer.Length; i++)
        {   
            if (buffer[i] == '\r')
            {
                end = i;                           
            }    
        }                                  
    }

    GPSMessage += new String(System.Text.Encoding.UTF8.GetChars(Utility.ExtractRangeFromArray(buffer, 0, end)));
    GPSMessage.TrimEnd();
    if (GPSMessage != "")
    {
        Debug.Print(GPSMessage); 
    }

    buffer = Utility.ExtractRangeFromArray(buffer, end, buffer.Length - end);
}

Upvotes: 0

Views: 304

Answers (2)

Yoopergeek
Yoopergeek

Reputation: 5642

End of line differs upon your platform, it can be \r, \r\n, or \n. Environment.NewLine will be whatever the end-of-line character is for your compilation platform.

Try a simple replace to strip out the new-lines perhaps?

string foo = GetSomeSortOfMultilineText();
foo = foo.Replace(Environment.NewLine, String.Empty);

Not sure if this fits what you're trying to do entirely, but...there you go. :)

Upvotes: 1

Daniel Rose
Daniel Rose

Reputation: 17648

Trimming returns the trimmed text. Change to:

GPSMessage = GPSMessage.TrimEnd();

Upvotes: 7

Related Questions