473,472 Members | 2,173 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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

9 New Member
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. ^^
Oct 19 '11 #1

✓ answered by GaryTexmo

Ok, so your Environment.NewLine 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.NewLine 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...
Expand|Select|Wrap|Line Numbers
  1. string input = "Hello guys" + Environment.NewLine + "how are you?";
Then we can process it and output some result...
Expand|Select|Wrap|Line Numbers
  1. string[] lines = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
  2. int numLines = lines.Length;
  3.  
  4. for (int i = 0; i < numLines; i++)
  5.     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).

16 8083
GaryTexmo
1,501 Recognized Expert Top Contributor
An enter, or return, character in C# code is represented usually by a '\n' character, though sometimes the string "\r\n" (contained in Environment.NewLine) 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.NewLine is used or just '\n', you can probably do a check... something like:

Expand|Select|Wrap|Line Numbers
  1. string[] results = null;
  2. if (testString.Contains(Environment.NewLine))
  3. {
  4.   // split using Environment.NewLine, assign to results
  5. }
  6. else
  7. {
  8.   // split using '\n', assign to results
  9. }
  10.  
  11. // 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...

Expand|Select|Wrap|Line Numbers
  1. 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 StringSplitOptions. This is an enum with two entries, None and RemoveEmptryEntries (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.
Oct 19 '11 #2
robin voo
9 New Member
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?
Oct 19 '11 #3
GaryTexmo
1,501 Recognized Expert Top Contributor
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.
Oct 19 '11 #4
robin voo
9 New Member
i hope you understand the function of the program

1.Formclas:
Expand|Select|Wrap|Line Numbers
  1. public partial class Form1 : Form
  2.     {
  3.         string[] textspeicher;
  4.         int codeeins, codezwei;
  5.         public Form1()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.  
  10.         private void button1_Click(object sender, EventArgs e)
  11.         {
  12.             try
  13.             {
  14.                 codeeins = Convert.ToInt32(textBox2.Text);
  15.                 codezwei = Convert.ToInt32(textBox3.Text);
  16.  
  17.                 openFileDialog1.ShowDialog();
  18.                 string filename = openFileDialog1.FileName;
  19.  
  20.                 StreamReader sr = new StreamReader(filename);
  21.                 string araystring = sr.ReadToEnd();
  22.                 sr.Close();
  23.  
  24.                 string[] textaray = araystring.Split(new char[] { '\n' });
  25.                 int laenge = textaray.Count();
  26.                 int i = 0;
  27.  
  28.                 while ((laenge - 1) >= i)
  29.                 {
  30.                     textBox1.Text = textBox1.Text + Verschluessler.entschluesseln(textspeicher[i], codezwei, codeeins);
  31.                     i++;
  32.                 }
  33.             }
  34.             catch
  35.             {
  36.                 MessageBox.Show("Fehler", "Error");
  37.             }
  38.  
  39.         }
  40.  
  41.         private void button2_Click(object sender, EventArgs e)
  42.         {
  43.             try
  44.             {
  45.                 codeeins = Convert.ToInt32(textBox2.Text);
  46.                 codezwei = Convert.ToInt32(textBox3.Text);
  47.  
  48.                 string araystring = textBox1.Text;
  49.                 string[] textaray = araystring.Split('\n');
  50.                 int laenge = textaray.Count();
  51.                 int i = 0;
  52.                 int s = 0;
  53.  
  54.                 while ((laenge-1) >= i)
  55.                 {
  56.                     textspeicher[i] = Verschluessler.verschluesseln(textaray[0], codezwei, codeeins);
  57.                     i++;
  58.                 }
  59.                 string finalerspeicher = "";
  60.                 while(s<= i)
  61.                 {
  62.                     finalerspeicher = finalerspeicher + textspeicher[s] + "\n";
  63.                     s++;
  64.                 }
  65.                 saveFileDialog1.ShowDialog();
  66.                 string filename = saveFileDialog1.FileName;
  67.  
  68.                 StreamWriter sr = new StreamWriter(filename);
  69.                 sr.Write(finalerspeicher);
  70.                 sr.Close();
  71.             }
  72.             catch
  73.             {
  74.                 MessageBox.Show("Fehler", "Error");
  75.             }
  76.         }
  77.     }
The "Verschluessler"clas:
Expand|Select|Wrap|Line Numbers
  1. class Verschluessler
  2.     {
  3.         public static string verschluesseln(string text, int verschiebung, int startverschiebung)
  4.         {
  5.             string neuertext = null;
  6.             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~Ü~²~³~{~[~]~}~\~@";
  7.             string[] abcgesplittet = abc.Split('~');
  8.             abcgesplittet[abcgesplittet.Count() - 1] = '"'.ToString();
  9.             abcgesplittet[abcgesplittet.Count() - 1] = "~";
  10.  
  11.             ArrayList Zeichenliste = new ArrayList();
  12.             Zeichenliste.AddRange(abcgesplittet);
  13.  
  14.             ArrayList newZeichenliste = new ArrayList();
  15.             newZeichenliste.AddRange(abcgesplittet);
  16.  
  17.             int i = 0;
  18.             while (i < startverschiebung)
  19.             {
  20.                 newZeichenliste.Add(newZeichenliste[0].ToString());
  21.                 newZeichenliste.RemoveAt(0);
  22.                 i++;
  23.             }
  24.  
  25.             i = 0;
  26.             while (i < text.Length)
  27.             {
  28.                 int ia = 0;
  29.                 while (ia < verschiebung)
  30.                 {
  31.                     newZeichenliste.Add(newZeichenliste[0].ToString());
  32.                     newZeichenliste.RemoveAt(0);
  33.                     ia++;
  34.                 }
  35.                 int element = Zeichenliste.IndexOf(text.Substring(i,1));
  36.                 neuertext = neuertext + newZeichenliste[element].ToString();
  37.                 i++;
  38.             }
  39.             return (neuertext);
  40.  
  41.         }
  42.  
  43.         public static string entschluesseln(string text, int verschiebung, int startverschiebung)
  44.         {
  45.             string neuertext = null;
  46.             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~Ü~²~³~{~[~]~}~\~@";
  47.             string[] abcgesplittet = abc.Split('~');
  48.             abcgesplittet[abcgesplittet.Count() - 1] = '"'.ToString();
  49.             abcgesplittet[abcgesplittet.Count() - 1] = "~";
  50.  
  51.             ArrayList Zeichenliste = new ArrayList();
  52.             Zeichenliste.AddRange(abcgesplittet);
  53.  
  54.             ArrayList newZeichenliste = new ArrayList();
  55.             newZeichenliste.AddRange(abcgesplittet);
  56.  
  57.             int i = 0;
  58.             while (i < startverschiebung)
  59.             {
  60.                 newZeichenliste.Insert(0, newZeichenliste[newZeichenliste.Count - 1].ToString());
  61.                 newZeichenliste.RemoveAt(newZeichenliste.Count - 1);
  62.                 i++;
  63.             }
  64.  
  65.             i = 0;
  66.             while (i < text.Length)
  67.             {
  68.                 int ia = 0;
  69.                 while (ia < verschiebung)
  70.                 {
  71.                     newZeichenliste.Insert(0, newZeichenliste[newZeichenliste.Count - 1].ToString());
  72.                     newZeichenliste.RemoveAt(newZeichenliste.Count - 1);
  73.                     ia++;
  74.                 }
  75.                 int element = Zeichenliste.IndexOf(text.Substring(i, 1));
  76.                 neuertext = neuertext + newZeichenliste[element].ToString();
  77.                 i++;
  78.             }
  79.             return (neuertext);
  80.         }
  81.     }
the problem is that the "Verschlüssler" 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 ^^
Oct 20 '11 #5
shilpa george
15 New Member
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.Split(new char[] { '\0' });
Oct 20 '11 #6
robin voo
9 New Member
mhh i tried to find the error with try blocks and i found it:

its in this part:
Expand|Select|Wrap|Line Numbers
  1. string araystring = textBox1.Text;
  2. string[] textaray = araystring.Split('\0'); /* you can use \n or \0*/
  3. int laenge = textaray.Count();
  4. int i = 0;
  5. int s = 0;
  6. try
  7. {
  8.     while ((laenge-1) >= i)
  9.     {
  10.          textspeicher[i] = Verschluessler.verschluesseln(textaray[i], codezwei, codeeins); //in this line there is the mistake.
  11.          i++;
  12.      }
Oct 20 '11 #7
GaryTexmo
1,501 Recognized Expert Top Contributor
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.NewLine 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.NewLine 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...

Expand|Select|Wrap|Line Numbers
  1. string output = "";
  2. foreach (char c in textBox1.Text)
  3. {
  4.   if (output != "") output += ", ";
  5.   output += ((int)c).ToString();
  6. }
  7. MessageBox.Show(output, "NewLine from textbox...);
  8.  
  9. output = "";
  10. foreach (char c in Environment.NewLine)
  11. {
  12.   if (output != "") output += ", ";
  13.   output += ((int)c).ToString();
  14. }
  15. 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.NewLine 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.NewLine). Lets see what you get before we make any more assumptions about what you'll be using to separate your lines :)
Oct 20 '11 #8
robin voo
9 New Member
I got 13,10 too and yes i am speaking german .
Oct 20 '11 #9
robin voo
9 New Member
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 "codecompiler"

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...789AC" 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
Oct 20 '11 #10
GaryTexmo
1,501 Recognized Expert Top Contributor
Ok, so your Environment.NewLine 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.NewLine 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...
Expand|Select|Wrap|Line Numbers
  1. string input = "Hello guys" + Environment.NewLine + "how are you?";
Then we can process it and output some result...
Expand|Select|Wrap|Line Numbers
  1. string[] lines = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
  2. int numLines = lines.Length;
  3.  
  4. for (int i = 0; i < numLines; i++)
  5.     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).
Oct 20 '11 #11
GaryTexmo
1,501 Recognized Expert Top Contributor
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:
Expand|Select|Wrap|Line Numbers
  1. for (<flag variable><increment statement><end condition>)
  2. {
  3.   // statements
  4. }
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...
Expand|Select|Wrap|Line Numbers
  1. while ((laenge-1) >= i)
  2. {
  3.   textspeicher[i] = Verschluessler.verschluesseln(textaray[i], codezwei, codeeins); //in this line there is the mistake.
  4.   i++;
  5. }
... can be rewritten as...

Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i <= laenge - 1; i++)
  2. {
  3.   textspeicher[i] = Verschluessler.verschlusseln(textaray[i], codezwei, codeins);
  4. }
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 :)
Oct 20 '11 #12
robin voo
9 New Member
GUY YOU ARE THE BEST ONE !!!!

NO errors in the programm ^^. no buggs ( i dont know may i find some ^^)
Oct 20 '11 #13
GaryTexmo
1,501 Recognized Expert Top Contributor
I'm confused... what was the solution? To use Environment.NewLine?
Oct 20 '11 #14
robin voo
9 New Member
Expand|Select|Wrap|Line Numbers
  1. 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" :)
Oct 20 '11 #15
GaryTexmo
1,501 Recognized Expert Top Contributor
Ah thanks for clarifying :)

Now, I checked into it and your line with '\n' splitting should have worked, so whatever error you were getting was by your processing class, Verschluessler. You might want to look into that.

Either way, glad you've got it figure out :)
Oct 20 '11 #16
GaryTexmo
1,501 Recognized Expert Top Contributor
Oh also, just so you know where it is, I made a request to have your question regarding how to have a safe file dialog box specify txt files moved to another thread. We prefer to separate questions here so that people can more easily find solutions :)

A moderator was kind enough to take care of this and your question can now be found here:
http://bytes.com/topic/c-sharp/answe...ave-txt-ending
Oct 20 '11 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Hrvoje Voda | last post by:
How to get a list of names from database into string array? variable name should be string array... This is the code I use... public string GetFunctionName(Guid UserID) {
4
by: Crirus | last post by:
There is a function somewhere to split a string with multiple tokens at a time? Say I have this: aaaa#bbbbb*ccccc$dddd I whould like to split it so the result whould be aaaa bbb
6
by: Bruce Wiebe | last post by:
Hi all I have a string that contains a list of email addresses in the format {"X@y.com","x@y.com"} and i need to convert it to a string array in the same format so my array would loook like ...
2
by: jack | last post by:
Hello, I need to plit: "1,34,54,123,34" Into an array list. Thanks for any help, Jack
8
by: Dave | last post by:
Greetings, Is there a way I can split a string into an array on a space OR a carriage return? What would the code look like for this? Thanks, -Dave
2
by: Digital Fart | last post by:
following code would split a string "a != b" into 2 strings "a" and "b". but is there a way to know what seperator was used? string charSeparators = { "=", ">=", "<=" , "!=" }; string s1 =...
12
by: Pascal | last post by:
hello and soory for my english here is the query :"how to split a string in a random way" I try my first shot in vb 2005 express and would like to split a number in several pieces in a random way...
17
by: AMP | last post by:
Hello I get 2 errors in the following code that I cant Debug without some help. They are both in the TryParse function. Seems simple enough.The Errors are Below. private void...
4
by: =?Utf-8?B?aXdkdTE1?= | last post by:
hi, im having a small issue. I pass a String object to a method, but then when i try to use the Split method of a String array, it says System.Array does not contain Split. The parameter of my...
6
by: Studlyami | last post by:
Okay, i have developed a file parser in C++ that i am trying to being into a c# program which is proving to be a lot more difficult than i thought. first i scan a file (which i opened using a...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.