C# - String.Split() Remove last item

14,156

Solution 1

This might work (untested):

string[] lines = richTextBox2.Text.Split('\n');
for( int i = 0; i < lines.Length; i ++ )
{
    lines[i] = lines[i].Trim(); //remove white space
    lines[i] = lines[i].substring(0, lines[i].LastIndexOf(' ');
}
string masterLine = String.Join(Environment.NewLine, lines);

Solution 2

This is a fixed-width layout, so you can accomplish what you want simply by cutting off all the content to the right of the fifth column:

string[] lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length; ++i)
{
    lines[i] = lines[i].Substring(0, 43);
}

Example input file:

J6      INT-00113G  227.905  174.994  180  SOIC8    
J3      INT-00113G  227.905  203.244  180  SOIC8     
U13     EXCLUDES    242.210  181.294  180  QFP128    
U3      IC-00276G   236.135  198.644  90   BGA48     
U12     IC-00270G   250.610  201.594  0    SOP8      
J1      INT-00112G  269.665  179.894  180  SOIC16    
J2      INT-00112G  269.665  198.144  180  SOIC16    

Output:

J6      INT-00113G  227.905  174.994  180  
J3      INT-00113G  227.905  203.244  180  
U13     EXCLUDES    242.210  181.294  180  
U3      IC-00276G   236.135  198.644  90   
U12     IC-00270G   250.610  201.594  0    
J1      INT-00112G  269.665  179.894  180  
J2      INT-00112G  269.665  198.144  180  

Solution 3

You are not saying what doesn't work..using the Lines property you could do something like this:

richTextBox2.Lines = richTextBox2.Lines
                                 .Select( l => string.Join(" ", l.Split(' ')
                                                     .Take(5)))
                                 .ToArray();

This would only work of course if the space only occurs as separator between columns.

Solution 4

This ones fairly easy to read ....

        string data = "J6      INT-00113G  227.905  174.994  180  SOIC8\r\nJ3      INT-00113G  227.905  203.244  180  SOIC8\r\nU13     EXCLUDES    242.210  181.294  180  QFP128\r\nU3      IC-00276G   236.135  198.644  90   BGA48\r\nU12     IC-00270G   250.610  201.594  0    SOP8\r\nJ1      INT-00112G  269.665  179.894  180  SOIC16\r\nJ2      INT-00112G  269.665  198.144  180  SOIC16\r\n";

        // Split on new line
        string[] lines = data.Split(new string[] {"\r\n"}, int.MaxValue, StringSplitOptions.RemoveEmptyEntries);

        StringBuilder result = new StringBuilder();

        foreach (string line in lines)
        {
            // Find the last space in the line
            int lastSpace = line.LastIndexOf(' ');

            // delete the end of the string from the last space
            string newLine = line.Remove(lastSpace);

            // rebuild string using stringBuilder
            result.AppendLine(newLine);
        }

        Console.WriteLine("Old List:");
        Console.Write(data);

        Console.WriteLine("New List:");
        Console.Write(result);
    }

This one is probably close to O(n):

        StringBuilder result = new StringBuilder();
        string data = "J6      INT-00113G  227.905  174.994  180  SOIC8\r\nJ3      INT-00113G  227.905  203.244  180  SOIC8\r\nU13     EXCLUDES    242.210  181.294  180  QFP128\r\nU3      IC-00276G   236.135  198.644  90   BGA48\r\nU12     IC-00270G   250.610  201.594  0    SOP8\r\nJ1      INT-00112G  269.665  179.894  180  SOIC16\r\nJ2      INT-00112G  269.665  198.144  180  SOIC16\r\n";

        // Split on new line
        int startchar = 0;
        int lastspace = 0;

        for(int i = 0; i < data.Length - 1; i++)
        {
            char current = data[i];

            if (current == ' ')
            {
                // remember last space
                lastspace = i;
            }
            else if (current == '\n')
            {
                result.AppendLine(data.Substring(startchar, lastspace - startchar));

                if(i != data.Length - 1)
                {
                    startchar = i + 1;
                    lastspace = startchar;
                }
            }
        }


        Console.Write(result.ToString());
Share:
14,156
theNoobGuy
Author by

theNoobGuy

Updated on August 20, 2022

Comments

  • theNoobGuy
    theNoobGuy almost 2 years

    I have a RTB that is loaded with a file that looks like this:

    J6      INT-00113G  227.905  174.994  180  SOIC8    
    J3      INT-00113G  227.905  203.244  180  SOIC8     
    U13     EXCLUDES    242.210  181.294  180  QFP128    
    U3      IC-00276G   236.135  198.644  90   BGA48     
    U12     IC-00270G   250.610  201.594  0    SOP8      
    J1      INT-00112G  269.665  179.894  180  SOIC16    
    J2      INT-00112G  269.665  198.144  180  SOIC16    
    

    I want to remove the last column using the string.Split() method.

    So far I have:

    // Splits the lines in the rich text boxes
    string[] lines = richTextBox2.Text.Split('\n');
    
    foreach (var newLine in lines)
    {
         newLine.Split(' ');
         line = line[0] + line[1] + line[2] + line[3] + line[4];  #This is the code that does not work.
    }
    

    However this does not work... does anyone know the problem and how to do this properly so the file looks like this?:

    J6      INT-00113G  227.905  174.994  180      
    J3      INT-00113G  227.905  203.244  180       
    U13     EXCLUDES    242.210  181.294  180     
    U3      IC-00276G   236.135  198.644  90      
    U12     IC-00270G   250.610  201.594  0         
    J1      INT-00112G  269.665  179.894  180     
    J2      INT-00112G  269.665  198.144  180    
    

    EDIT: I also think that I need to string.Split(' ') each line that is already split?

  • theNoobGuy
    theNoobGuy almost 13 years
    Now that I look at my code posted, I am splitting each line in the string. So every string will look similar to this: J1 INT-00112G 269.665 179.894 180 SOIC16. However, I need to then split that line by something like .Split(' ') so it splits it by spaces to get new strings.. I will post updated code above... But pretty much I can't do: line[0] + line[1]...;
  • iandotkelly
    iandotkelly almost 13 years
    This is the best solution as it doesn't rely on knowing what character to split at - such as the 41 or 43 used in some solutions
  • theNoobGuy
    theNoobGuy almost 13 years
    If it is not a fixed width how can I go about this?
  • Dan Tao
    Dan Tao almost 13 years
    @iandotkelly: You're making some assumptions in declaring this the "best" solution based on the reasons stated. Only the OP knows exactly what behavior he wants. For example, suppose the file format might change such that another column is added and he wants that column to be ignored also. Then this solution would no longer work, but the fixed-width cut-off approach still would. Of course, scenarios illustrating the opposite case could easily be concocted as well. It all depends on exactly what the goal is.
  • Dan Tao
    Dan Tao almost 13 years
    @Colton: Mannimarco's answer ought to help you out in that case. (However, if it's not a fixed-width layout then why did you supply us with fictional input?)
  • theNoobGuy
    theNoobGuy almost 13 years
    @Mannimarco: This does what I need it to! Dan Tao +1 for being correct about the OP knowing what is needed.
  • Coeffect
    Coeffect almost 13 years
    @Dan Tao: True about the columns. Removing two columns this way would be a pain. I just hate counting characters =p
  • theNoobGuy
    theNoobGuy almost 13 years
    This works, but not guarenteed for an unfixed width. Thank you though.
  • Dan Tao
    Dan Tao almost 13 years
    @Mannimarco: It would be more efficient to call string.Join(Environment.NewLine, lines) on the subsequent array rather than perform multiple string concatenations with +=.
  • iandotkelly
    iandotkelly almost 13 years
    @DanTao - true, but it strikes me that its more likely that the width of columns would change more than new columns get added. Based on the very small amount of data provided here - I wouldn't be confident choosing any particular magic number to split at. Splitting at the last column delimiter seems more robust.
  • Dan Tao
    Dan Tao almost 13 years
    @iandotkelly: Well, it's moot now; the OP has himself stated that the format is not guaranteed to be fixed-width and so this is the appropriate solution for him! That said, I think the important point is that, faced with the problem as described, a developer would be wise to first establish exactly what valid assumptions can be made about the input data (i.e., with the business, customer, data vendor, or whomever) before finalizing a solution. Otherwise all we can do is speculate what is more or less likely.
  • theNoobGuy
    theNoobGuy almost 13 years
    @Dan Tao: Agreed. @Mannimarco: I fixed an error by replacing your line with lines[i] = lines[i].substring(0, lines[i].LastIndexOf(' ') + 1);
  • Dan Tao
    Dan Tao almost 13 years
    @Colton: Why? You want to include an extra space character in your output?
  • theNoobGuy
    theNoobGuy almost 13 years
    @Dan Tao: If it is not in there then it errors stating: "Length cannot be less than zero. Parameter name: length"
  • Dan Tao
    Dan Tao almost 13 years
    @Colton: In that case then you have some lines with no whitespace characters in them. So the solution above will still not work; it will just give you a blank line in such cases. Is it possible your columns are delimited with tab characters rather than spaces? If so you could try LastIndexOfAny with ' ' and \t.