-1

How can I reverse string lines? Not a text file. String tekstGecmis is : "1\r\n2\r\n3\r\n"

1

2

3

To:

3

2

1

I tried

string son = String.Empty;
StringBuilder ters = new StringBuilder();
for (int i = 1; i < 4; i++)
{
    string[] lines = tekstGecmis.Split('\r','\n');
    string last_line = lines[lines.Length - i];
    
    ters.AppendLine(son + last_line);
    
    son = ters.ToString();
}
Community
  • 1
  • 1
  • Change this part `tekstGecmis.Split('\r','\n');` – Farzin Kanzi Feb 04 '17 at 12:28
  • There are plenty of questions and documentation about reversing lists/arrays/... - when asking questions author is expected to demonstrate what they found researching the solution and how it did not work in they case. – Alexei Levenkov Feb 05 '17 at 05:57

5 Answers5

4

you can try this

string text = "1\r\n2\r\n3\r\n";

Console.WriteLine(string.Join("\r\n", text.Split('\r','\n').Reverse()));

working example

1

You can simply use the Reverse and string.Join methods. Like this:

string result = string.Join("",son.Reverse());

Result:

3

2

1

Community
  • 1
  • 1
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
0

This will turn "1\r\n2\r\n3\r\n" into "3\r\n2\r\n1\r\n", which is what I think you're trying to do:

str = string.Join("\r\n",
    str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Reverse());
itsme86
  • 19,266
  • 4
  • 41
  • 57
0

You can do this:

string str1 = "1\r\n12\r\n31";
        string[] lines = str1.Split(new char[]{'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
        lines = lines.Reverse().ToArray();
        string result = string.Join("\r\n", lines);
Farzin Kanzi
  • 3,380
  • 2
  • 21
  • 23
0
  1. Split the string before the cycle

  2. Inverse the cycle's direction

  3. Calculate ters after the cycle

string son = String.Empty; StringBuilder ters = new StringBuilder(); string[] lines = tekstGecmis.Split('\r','\n'); for (int i = 3; i >= 0; i--) { ters.AppendLine(lines[i]); } son = ters.ToString();

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175