How to split out a "Enterkey" of a string /- array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • robin voo
    New Member
    • Oct 2011
    • 9

    How to split out a "Enterkey" of a string /- array

    Hey,

    I have a problem. I want to split a string like
    "Hello Guys,
    welkome to my home".

    The Probem is, that i want to get this string and save it in a array. But, i want that the first line is in the index 0 and the second line in index 2. So i need to .Split it.

    But what do i write in the ( )?

    Thanks for answers
    _______________ _______________ _____________
    Sorry for my very bad english. ^^
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    An enter, or return, character in C# code is represented usually by a '\n' character, though sometimes the string "\r\n" (contained in Environment.New Line) is used as well. There's a lot of ways you can approach this but you should probably start by looking at the methods available on the String class.

    If you look at Split, you can see that it takes a character or string and returns an array of strings, which is very similar to what you're looking for. Now the slight catch here is that you've stated you want the first line in index 0 of your array, and the second line in index 2, which means you want index 1 empty? If that's correct and not a typo, you'll likely just have to run the split, then copy the strings into the appropriate place later.

    To resolve the uncertainty as to whether or not an Environment.New Line is used or just '\n', you can probably do a check... something like:

    Code:
    string[] results = null;
    if (testString.Contains(Environment.NewLine))
    {
      // split using Environment.NewLine, assign to results
    }
    else
    {
      // split using '\n', assign to results
    }
    
    // results will have your split data at this point
    One more thing to be aware of... I believe one of the overloads of String.Split takes a string but the other takes a char array. You can just define the char array in the call doing something like...

    Code:
    string[] results = testString.Split(new char[] { '\n' });
    If you want to split on more than one character you can just include it in that array by separating the items with commas. Also be aware of the second parameter of the string.Split method, which is StringSplitOpti ons. This is an enum with two entries, None and RemoveEmptryEnt ries (or something to that effect, intellisense will get it for you :P). If the latter is set, it will just remove all empty lines from the resulting array. This would occur when you had two tokens (that you are splitting on) right next to each other.

    Comment

    • robin voo
      New Member
      • Oct 2011
      • 9

      #3
      thanks for your answer. Your english is hard to understand ^^. In any case, I tested it with the '\n' but it gives errors.

      i try to explane what i mean:
      Sting text is a multiline textbox.
      e.g.:
      "Hello guys
      how are you?"

      now i want to save the lines in the same string array but in another index.
      in this example textarray[0] = Hello guys"
      textarray [1] = "How are you?"
      how can i solve this problem?

      Comment

      • GaryTexmo
        Recognized Expert Top Contributor
        • Jul 2009
        • 1501

        #4
        I'm guessing that English isn't your first language because of your first post and subsequent comment, so lets try reducing the language barrier. Can you copy/paste the code you have and the error it generated?

        I'd like to see what you tried and then perhaps I can help you understand the error you got.

        Comment

        • robin voo
          New Member
          • Oct 2011
          • 9

          #5
          i hope you understand the function of the program

          1.Formclas:
          Code:
          public partial class Form1 : Form
              {
                  string[] textspeicher;
                  int codeeins, codezwei;
                  public Form1()
                  {
                      InitializeComponent();
                  }
                  
                  private void button1_Click(object sender, EventArgs e)
                  {
                      try
                      {
                          codeeins = Convert.ToInt32(textBox2.Text);
                          codezwei = Convert.ToInt32(textBox3.Text);
                      
                          openFileDialog1.ShowDialog();
                          string filename = openFileDialog1.FileName;
          
                          StreamReader sr = new StreamReader(filename);
                          string araystring = sr.ReadToEnd();
                          sr.Close();
          
                          string[] textaray = araystring.Split(new char[] { '\n' });
                          int laenge = textaray.Count();
                          int i = 0;
                      
                          while ((laenge - 1) >= i)
                          {
                              textBox1.Text = textBox1.Text + Verschluessler.entschluesseln(textspeicher[i], codezwei, codeeins);
                              i++;
                          }
                      }
                      catch
                      {
                          MessageBox.Show("Fehler", "Error");
                      }
                      
                  }
          
                  private void button2_Click(object sender, EventArgs e)
                  {
                      try
                      {
                          codeeins = Convert.ToInt32(textBox2.Text);
                          codezwei = Convert.ToInt32(textBox3.Text);
                      
                          string araystring = textBox1.Text;
                          string[] textaray = araystring.Split('\n');
                          int laenge = textaray.Count();
                          int i = 0;
                          int s = 0;
                      
                          while ((laenge-1) >= i)
                          {
                              textspeicher[i] = Verschluessler.verschluesseln(textaray[0], codezwei, codeeins);
                              i++;
                          }
                          string finalerspeicher = "";
                          while(s<= i)
                          {
                              finalerspeicher = finalerspeicher + textspeicher[s] + "\n";
                              s++;
                          }
                          saveFileDialog1.ShowDialog();
                          string filename = saveFileDialog1.FileName;
          
                          StreamWriter sr = new StreamWriter(filename);
                          sr.Write(finalerspeicher);
                          sr.Close();
                      }
                      catch
                      {
                          MessageBox.Show("Fehler", "Error");
                      }
                  }
              }
          The "Verschluessler "clas:
          Code:
          class Verschluessler
              {
                  public static string verschluesseln(string text, int verschiebung, int startverschiebung)
                  {
                      string neuertext = null;
                      string abc = @" ~1~2~3~4~5~6~7~8~9~0~!~§~$~%~&~/~(~)~=~?~´~`~#~'~+~*~/~-~^~°~,~;~.~:~-~_~<~>~|~y~x~c~v~b~n~m~Y~X~C~V~B~N~M~a~s~d~f~g~h~j~k~l~ö~ä~A~S~D~F~G~H~J~K~L~Ö~Ä~q~w~e~r~t~z~u~i~o~p~ü~Q~W~E~R~T~Z~U~I~O~P~Ü~²~³~{~[~]~}~\~@";
                      string[] abcgesplittet = abc.Split('~');
                      abcgesplittet[abcgesplittet.Count() - 1] = '"'.ToString();
                      abcgesplittet[abcgesplittet.Count() - 1] = "~";
          
                      ArrayList Zeichenliste = new ArrayList();
                      Zeichenliste.AddRange(abcgesplittet);
          
                      ArrayList newZeichenliste = new ArrayList();
                      newZeichenliste.AddRange(abcgesplittet);
          
                      int i = 0;
                      while (i < startverschiebung)
                      {
                          newZeichenliste.Add(newZeichenliste[0].ToString());
                          newZeichenliste.RemoveAt(0);
                          i++;
                      }
          
                      i = 0;
                      while (i < text.Length)
                      {
                          int ia = 0;
                          while (ia < verschiebung)
                          {
                              newZeichenliste.Add(newZeichenliste[0].ToString());
                              newZeichenliste.RemoveAt(0);
                              ia++;
                          }
                          int element = Zeichenliste.IndexOf(text.Substring(i,1));
                          neuertext = neuertext + newZeichenliste[element].ToString();
                          i++;
                      }
                      return (neuertext);
          
                  }
          
                  public static string entschluesseln(string text, int verschiebung, int startverschiebung)
                  {
                      string neuertext = null;
                      string abc = @" ~1~2~3~4~5~6~7~8~9~0~!~§~$~%~&~/~(~)~=~?~´~`~#~'~+~*~/~-~^~°~,~;~.~:~-~_~<~>~|~y~x~c~v~b~n~m~Y~X~C~V~B~N~M~a~s~d~f~g~h~j~k~l~ö~ä~A~S~D~F~G~H~J~K~L~Ö~Ä~q~w~e~r~t~z~u~i~o~p~ü~Q~W~E~R~T~Z~U~I~O~P~Ü~²~³~{~[~]~}~\~@";
                      string[] abcgesplittet = abc.Split('~');
                      abcgesplittet[abcgesplittet.Count() - 1] = '"'.ToString();
                      abcgesplittet[abcgesplittet.Count() - 1] = "~";
          
                      ArrayList Zeichenliste = new ArrayList();
                      Zeichenliste.AddRange(abcgesplittet);
          
                      ArrayList newZeichenliste = new ArrayList();
                      newZeichenliste.AddRange(abcgesplittet);
          
                      int i = 0;
                      while (i < startverschiebung)
                      {
                          newZeichenliste.Insert(0, newZeichenliste[newZeichenliste.Count - 1].ToString());
                          newZeichenliste.RemoveAt(newZeichenliste.Count - 1);
                          i++;
                      }
          
                      i = 0;
                      while (i < text.Length)
                      {
                          int ia = 0;
                          while (ia < verschiebung)
                          {
                              newZeichenliste.Insert(0, newZeichenliste[newZeichenliste.Count - 1].ToString());
                              newZeichenliste.RemoveAt(newZeichenliste.Count - 1);
                              ia++;
                          }
                          int element = Zeichenliste.IndexOf(text.Substring(i, 1));
                          neuertext = neuertext + newZeichenliste[element].ToString();
                          i++;
                      }
                      return (neuertext);
                  }
              }
          the problem is that the "Verschlüss ler" clas can only handl stings with one line. And the textbox1 is a multiline textbox. So i want that the text is splitted.

          I hope you understand the program ^^

          Comment

          • shilpa george
            New Member
            • Oct 2011
            • 15

            #6
            hello robin,
            try to split the string with '\0'..because an ending of a string is usually denoted by '\0'...

            try this one. I hope it works.
            string[] textaray = araystring.Spli t(new char[] { '\0' });

            Comment

            • robin voo
              New Member
              • Oct 2011
              • 9

              #7
              mhh i tried to find the error with try blocks and i found it:

              its in this part:
              Code:
              string araystring = textBox1.Text;
              string[] textaray = araystring.Split('\0'); /* you can use \n or \0*/
              int laenge = textaray.Count();
              int i = 0;
              int s = 0;
              try
              {
                  while ((laenge-1) >= i)
                  {
                       textspeicher[i] = Verschluessler.verschluesseln(textaray[i], codezwei, codeeins); //in this line there is the mistake.
                       i++;
                   }

              Comment

              • GaryTexmo
                Recognized Expert Top Contributor
                • Jul 2009
                • 1501

                #8
                Your original code looks like what I'm expecting, though I would recommend you use the code from my first post where you check to see if the string contains Environment.New Line and split on that if it's available. If not try '\n'. For your second block of code there, can you please describe the error you are seeing? Please understand where we're coming from... you posted code and said there's a problem, but you didn't tell me what it is. You're effectively forcing me to run your code but in this case, due to platform differences, this is impossible. Make it easier for me to help you, post more details. Specifically, what is the exception?

                I'm not sure what language this is... German or something similar? This is why I suggested using Environment.New Line and splitting via string, just to make sure we get your language setting's newline character. I can't test this code because I don't have your language settings, and some things are just different.

                That said, there's an easy way to check what character/string you're looking for. Create a new program and put a multiline textbox on it. Then put a button. Put the following code in your button's click event...

                Code:
                string output = "";
                foreach (char c in textBox1.Text)
                {
                  if (output != "") output += ", ";
                  output += ((int)c).ToString();
                }
                MessageBox.Show(output, "NewLine from textbox...);
                
                output = "";
                foreach (char c in Environment.NewLine)
                {
                  if (output != "") output += ", ";
                  output += ((int)c).ToString();
                }
                MessageBox.Show(output, "Environment.NewLine");
                Then run your program, put your cursor in the textbox and press enter. Now click the button. You'll get two message boxes, one telling you the integer values of the characters in the textbox and another telling you the integer values of the characters in your Environment.New Line string.

                For example, if I run it on my English OS, I get the following in my message boxes...
                Message Box 1: "13, 10"
                Message Box 2: "13, 10"
                So in my case, when I press enter in a TextBox I don't get a '\n', I get a "\r\n" (which is Environment.New Line). Lets see what you get before we make any more assumptions about what you'll be using to separate your lines :)

                Comment

                • robin voo
                  New Member
                  • Oct 2011
                  • 9

                  #9
                  I got 13,10 too and yes i am speaking german .

                  Comment

                  • robin voo
                    New Member
                    • Oct 2011
                    • 9

                    #10
                    My programm's funktion is to creat a .txt data with the keyed text of the textbox1.
                    i start to explane the loading button: //button1

                    first step: reading the code 2numbers (int)

                    second step: starting the openFileDialog (choosing the .txt-file)

                    third step: splitting the converted text in the lines.

                    fouth step: sending every line to the compiler (with while) (decode)

                    fiveth step: send the normal text to the textbox1


                    now i explane the saveing button: //button 2

                    first step: Reading the "Code" in 2numbers (int)

                    second step: splitting the text in the lines.

                    third step: send each line to the "codecompil er"

                    fourth step: starting the saveFileDialog and saving the compiled text as a .txt

                    Now i explane the compiler: (creating the compiled text)
                    first step: creating a array with all letters and numbers and ". a.s.o.

                    second step: The first code number says how far the "ABC" should move to the behind.
                    e.g. "ABC.....XYZ123 .....789"
                    the first code is 2:
                    "C.....XYZ123.. ..789AB"

                    third step: Looking what "rang" the first letter has got in the "ABC" without the moving. then move the "C...XYZ123...7 89AC" with the number of code 2 + the "rang".

                    e.g. first letter is the B:
                    "rang" is 2 (because second letter in the ABC
                    the second code is e.g. 1
                    so move the "C....XYZ123... 789AB" 3 letters "F....XYZ123... 789ABCDE".

                    ps: the second method of the converter do the same in the opponent way ^^

                    i hope you can understand my very worst english (school mark = 4 :D)

                    thanks for your help

                    Comment

                    • GaryTexmo
                      Recognized Expert Top Contributor
                      • Jul 2009
                      • 1501

                      #11
                      Ok, so your Environment.New Line is the same as mine. Your split on '\n' should work but you'll still have an extra '\r' in there, so just try splitting on the Environment.New Line string. When you run your code above, is the value of laenge 2? If the input you provided is what is in your textbox, this should be so. We can do a quick test externally to verify...

                      Input:
                      "Hello guys
                      how are you?"
                      We can write this in code as...
                      Code:
                      string input = "Hello guys" + Environment.NewLine + "how are you?";
                      Then we can process it and output some result...
                      Code:
                      string[] lines = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                      int numLines = lines.Length;
                      
                      for (int i = 0; i < numLines; i++)
                          Console.WriteLine("Line " + i.ToString() + ": " + lines[i]);
                      When I run this, I get...
                      Line 0: Hello guys
                      Line 1: how are you?
                      So in addition to validating the value of your laenge variable, lets also make sure that you get the same output as me. If everything is working as expected, I'm wondering if there's something wrong with your call to Verschluessler. Have you validated that Verschluessler works with a single line?

                      Also, please tell me the error you get (exception message) from the code you posted above (with the try/catch block).

                      Comment

                      • GaryTexmo
                        Recognized Expert Top Contributor
                        • Jul 2009
                        • 1501

                        #12
                        Additionally, let me introduce you to the for loop construct. I notice you're using a lot of while loops to do the same thing and the for loops are a little less code and perhaps a bit easier to understand.

                        You can do a lot of tricks with for loops but lets stick with the basic format, which is:
                        Code:
                        [b]for[/b] ([i]<flag variable>[/i]; [i]<increment statement>[/i]; [i]<end condition>[/i])
                        {
                          // statements
                        }
                        It's important to note that you can define the variable in the flag variable section but you don't have to.

                        So, for example, your loop...
                        Code:
                        while ((laenge-1) >= i)
                        {
                          textspeicher[i] = Verschluessler.verschluesseln(textaray[i], codezwei, codeeins); //in this line there is the mistake.
                          i++;
                        }
                        ... can be rewritten as...

                        Code:
                        for (int i = 0; i <= laenge - 1; i++)
                        {
                          textspeicher[i] = Verschluessler.verschlusseln(textaray[i], codezwei, codeins);
                        }
                        You don't have to change it, I'm just bringing it to your attention.

                        Also, I see a few oddities in your Verschluessler. verschluesseln method (and similar in entschluesseln) .

                        Per the code you posted, lines 8 and 9 overwrite the last string in the array with '"' and '~' respectively. This is odd seeming to me.

                        Also, what is the purpose of lines 17 to 23? It looks like it's adding the first element of a list to the list, then removing it from the first element. The end effect here is that your list will be exactly the same as it was. Why are you doing this? You do similar on lines 28 to 34.

                        I think that's how it reads. Are you trying to reverse the array maybe? Sorry if I've misread these, I can't read/understand your variable names so they don't have meaning to me :)

                        Comment

                        • robin voo
                          New Member
                          • Oct 2011
                          • 9

                          #13
                          GUY YOU ARE THE BEST ONE !!!!

                          NO errors in the programm ^^. no buggs ( i dont know may i find some ^^)

                          Comment

                          • GaryTexmo
                            Recognized Expert Top Contributor
                            • Jul 2009
                            • 1501

                            #14
                            I'm confused... what was the solution? To use Environment.New Line?
                            Last edited by Niheel; Oct 20 '11, 04:50 PM. Reason: moved rest of answer to new question

                            Comment

                            • robin voo
                              New Member
                              • Oct 2011
                              • 9

                              #15
                              Code:
                              new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries
                              this was the solution ^^.

                              Thank you very very much, now i can show the program my classmembers and they make "O.O" :)

                              Comment

                              Working...