user5641102
user5641102

Reputation: 37

How to sort an array of strings taken from textbox1 and display the change in textbox2 in C#?

So, I've tried many different things but nothing seems to work - excuse my lack of knowledge - I'm pretty new to C#. The thing is, I'm supposed to make a little project to demonstrate how arrays work in C#.

I went with two textboxes, one for the input and the other one for the output. I'm trying to sort my string from textbox1 by length and to show the sorted array in textbox2. I'm open for suggestions - Array.Sort isn't doing its magic for me, I tried OrderBy as well, though I may have done it in the wrong way. Anyway, I'd appreciate your advice, guys

Here's an example of what I've tried.

string[] myArray= textBox.Text.Split(' '); 
textBox2.Text= myArray.OrderByDescending(s => s.Length);

if I have in textbox1

"I am driving a car"

I want my text in textbox2 to be

"Driving car am a I"

Upvotes: 1

Views: 589

Answers (3)

drewfiss90
drewfiss90

Reputation: 53

From my understanding, you are trying to sort the words in the first text box by length and output that in the second text box. You are on the right track with using split, but I would do the sorting and such manually rather than trying to use pre-built methods so you understand what is going on. Do something like this:

        string textBox1 = //text from text box 1
        string output = "";
        string[] s = textBox1.Split(' ');

        int itemsSorted = 0;
        while (true)
        {
            itemsSorted = 0;
            for (int i = 0; i < s.Length-1; i++)
            {
                if(s[i].Length > s[i+1].Length)
                {
                    string temp = s[i];
                    s[i] = s[i + 1];
                    s[i + 1] = temp;
                    itemsSorted++;
                }
            }
            if (itemsSorted == 0)
                break;
        }

        for(int i = 0;i < s.Length;i++)
        {
            output += s[i] + " ";
        }

        //trim trailing space if you would like
        //text box 2 text set to = output

This just implements a simple bubble sort to sort the length of words. Let me know if you have any questions.

Upvotes: 0

Tomasz Pikć
Tomasz Pikć

Reputation: 763

string[] myArray= textBox.Text.Split(" "); 
textBox2.Text= string.Join(" ", myArray.OrderByDescending(s => s.Length));

you were close :) just need to concatenate each string in your array to one string. As you can see you can use string.Join method. First argument is a seperator and second is array of strings. In this case - sorted list.

Upvotes: 2

Denis Bubnov
Denis Bubnov

Reputation: 2785

Use method Sort. For example: Array.Sort Method (Array)

Upvotes: 0

Related Questions