I have a textbox with multiline enabled, and want to add a string at the beginning and end of
each line, so every line would be changed to
a + line + b
Now I know it has to do with a foreach loop, but don't know how to write it out.
Well, the Lines property is probably the one you want. Three options:
string[] lines = textBox.Lines;
for (int i = 0; i < lines.Length; i++)
{
lines[i] = a + lines[i] + b;
}
textBox.Lines = lines;
Or:
textBox.Lines = Array.ConvertAll(textBox.Lines, line => a + line + b);
Or:
textBox.Lines = textBox.Lines
.Select(line => a + line + b)
.ToArray();
You can use a replace on the entire text:
text = a + text.Replace(Environment.NewLine, b + Environment.NewLine + a) + b;
Since you mentioned foreach, here's another way.
var newLines = new List<string>(textBox1.Lines.Length);
foreach (string line in textBox1.Lines)
newLines.Add(a + line + b);
textBox1.Lines = newLines.ToArray();
Here is what i use to add the characters a and b to the beginning and the end to a string that contains a bunch of lines :
public string Script;
string[] lines = Script.Split(new[] { '\r', '\n' });
for (int i = 0; i < lines.Length; i++)
{
lines[i] = a + lines[i] + b;
if (!lines[i].Equals("\"\"+"))
{
Console.WriteLine(lines[i]);
Result += lines[i]+"\n";
}
}
Related
Trying to get a simple 2 dimensional array to display to a text box. Output should look like this:
Student Class House
Jack Math Oxford
Bender Chem Trent
All previous attempts have failed and I am not sure how to output the code.
String[,] text = {
{ "Student", "Class", "House" },
{ "Jack", "Math", "Oxford" },
{ "Bender", "Chem", "Trent" } };
//string textString;
for (int i = 0; i < text.GetUpperBound(0); i++)
{
string first = text[i, 0];
string middle = text[i, 1];
string last = text[i, 2];
TextBox1.Text = first;
TextBox1.Text = middle;
TextBox1.Text = last;
}
You need to concatenate the text onto your strings and pass the strings to the texbox only once, after you're all done. You'll want to add in line breaks to have the data go over several lines as well.
Something like this (untested):
String[,] text = {
{ "Student", "Class", "House" },
{ "Jack", "Math", "Oxford" },
{ "Bender", "Chem", "Trent" } };
string output = '';
//string textString;
for (int i = 0; i < text.GetUpperBound(0); i++)
{
output += text[i, 0] + text[i, 1] + text[i, 2] + Environment.NewLine;
}
TextBox1.Text = output;
At the moment you're just adding things to the textbox and then overwriting them on the next loop.
so i think you problem that you are using textbox try textarea.
the reason is that textbox only take only line but textare you can have multiple lines and you are overwriting the text of the textbox every time by doing this TextBox1.Text = first;
TextBox1.Text = middle;
TextBox1.Text = last;
so try this better
TextBox1.Text += first + " " + middle+" " + last;
If both dimensions are dynamic, you can use a second loop nested it in the one you have. Each loop will be going through one dimension:
for (int i = 0; i < text.GetLength(0); i++)
{
for (int j = 0; j < text.GetLength(1); j++)
{
TextBox1Text += text[i, j] + "\t";
}
TextBox1.Text += "\r\n";
}
Note: I used tab \t to separate the columns and new line \r\n to separate the rows. However, this format will not be visible in a textbox, you'll need to use a textarea. Here is a demo.
I have a string in c#. I want to split that string into 2 words string sets like:
string str = "Split handles splitting upon string and character delimiters."
Output should be:
1: "Split handles"
2: "splitting upon"
3: "string and"
4: "character delimiters."
What should be the best method to do this?
Here is what i have tried yet:
private List<string> Spilt(string text)
{
List<string> bunch = new List<string>();
int block = 15;
string[] words = text.Split(' ');
int length = words.Length;
int remain = 0;
while(remain < length)
{
bunch.Add(string.Join(" ", words.Take(block)));
remain += block;
}
return bunch;
}
The simplest approach would be to split at each space, and then "re-join" the pairs back, like this:
var pairs = str.Split(' ')
.Select((s,i) => new {s, i})
.GroupBy(n => n.i / 2)
.Select(g => string.Join(" ", g.Select(p=>p.s)))
.ToList();
Demo on ideone.
Try this
string str = "Split handles splitting upon string and character delimiters.";
var strnew = str.Split(' ');
var strRes = string.Empty;
int j = 1;
for (int i = 0; i < strnew.Length; i=i+2)
{
strRes += j.ToString()+": " + #"""" + strnew[i] + " " + strnew[i+1] + #"""" +"\n" ;
j++;
}
Console.Write(strRes);
// print strRes
I want my form to display 1,2,3,4,5
but all it does is replace the text again and again.
for (int i = 1; i <= 5; i++)
{
richTextBox1.Text = Convert.ToString(i);
}
I know it's because of the .Text that it always overrides itself. But how can i leave them in the form so it will display:
1
2
3
4
5
The problem is that in your loop, you're completely replacing the text with each iteration. So the text is left with whatever the last value of i was.
Try putting adding to the current text (with +=) and putting a new line (Environment.NewLine or "\n") between each number:
for (int i = 1; i <= 5; i++)
{
richTextBox1.Text += Environment.NewLine + Convert.ToString(i);
}
Or alternatively, a little Linq can make your life a lot easier:
richTextBox1.Text = string.Join(Environment.NewLine, Enumerable.Range(1, 5));
Try this:
for (int i = 1; i <= 5; i++)
{
richTextBox1.Text += Convert.ToString(i) + Environment.NewLine;
}
Edit:
Just noticed that you want to print one number per line. \n is the NewLine character and will give you a carriage return on the end of the line.
Environment.NewLine is also a good choice, because it will give you the newline character based on the environment the app is running in.
append text, don't just assign it.
richTextBox1.Text += Convert.ToString(i);
this is equivelant of
richTextBox1.Text = richTextBox1.Text + Convert.ToString(i);
richTextBox1.AppendText(i.ToString()+Environment.NewLine);
This will also do:
for (int i = 1; i <= 5; i++)
{
richTextBox1.AppendText(i + Environment.NewLine);
}
I want to read a text file in order to build map.
For example I have this map:
0#0000000
0#0000000
0#0000000
000000000
000000000
000000000
000000000
I know I should use this:
StreamReader reader = new StreamReader(Application.StartupPath+#"/TestMap.MMAP");
string line = reader.ReadToEnd();
reader.Close();
Now, for example, I want read line 2 char "#". how can i do this?
please help me.
Solved:
Thank you (#L.B AND #user861114), at last my problem was solved:
string[,] item = new string[9, 7];
string[] line = File.ReadAllLines(Application.StartupPath + #"/TestMap.MMAP");
for (int j = 0; j < 7; j++)
{
for (int i = 0; i < 9; i++)
{
item[i, j] = line[j].Substring(i, 1);
Console.WriteLine(i + " " + j + "=" + item[i, j]);
}
}
string[] lines = File.ReadAllLines(your path);
then you can access
char ch = lines[1][1]; //second line's second char
I think it's little bit easy :
string[] strs = string.split(myString, "\n"); // split to array of string by delimiter endline
char[] chars = strs[1].ToCharArray(); // you can get second char "#"
I'm trying to create a loop to avoid copy pasting these lines 30 times.
The names are:
sum1 to sum30
br1txt1 to br30txt1
br1txt2 to br30txt2
//decimal sum30 = decimal.Parse(br30txt1.Text) + decimal.Parse(br30txt2.Text);
//sumTxt30.Text = sum30.ToString();
But the error I'm getting is that the textbox array seems to try to put the value of the textbox not the text box refrenc it self in to the array, how should I fix this?
private void sumX()
{
TextBox[] sumTextboxNames;
sumTextboxNames = new TextBox[29];
for (int i = 1; i < 31; i++)
{
if (sumTextboxNames[0] == null)
{
int y = 0;
foreach (Control c in this.Controls)
{
if (c is TextBox && c.Name.StartsWith("sum"))
{
sumTextboxNames[y] = (TextBox)c;
y++;
}
}
}
else
{
}
string1 = "br" + i + "txt" + 1 + ".Text";
string2 = "br" + i + "txt" + 2 + ".Text";
string3 = "sumTxt" + i + ".Text";
sum = decimal.Parse(string1) + decimal.Parse(string2);
int x = i - 1;
sumTextboxNames[x].Text = sum.ToString();
}
}
The following lines won't work at all:
string1 = "br" + i + "txt" + 1 + ".Text";
string2 = "br" + i + "txt" + 2 + ".Text";
As 1 and 2 are not strings and can not be concatenated to a string. That should give a compiler error right away.
In the following line, you're trying to add up the names of the text boxes as numbers - won't work, the names contain non-number characters.
sum = decimal.Parse(string1) + decimal.Parse(string2);
Anyway, you don't need to use the TextBox array at all. What you could do is:
for (int i = 1; i <= 30; i++)
{
TextBox s = (TextBox)this.Controls[<Name for the S-Textbox>];
TextBox b1 = (TextBox)this.Controls[<Name for the first sum textbox>];
TextBox b2 = (TextBox)this.Controls[<Name for the second sum textbox>];
s.Text = Decimal.Parse(b1.Text) + Decimal.Parse(b2.Text);
}
EDIT
Sorry, quoted wrong line from OP's source code.
EDIT 2
Forgot to cast to TextBox - this is required of course... Thanks for pointing it out, everybody.
Thorsten Dittmar's answers is the way you should go.
However, with respect to this code:
foreach (Control c in this.Controls)
{
if (c is TextBox && c.Name.StartsWith("sum"))
{
sumTextboxNames[y] = (TextBox)c;
y++;
}
}
You should try a solution that uses LINQ.
For example
TextBox [] sumTextBoxes = (from t in this.Controls.Cast<Control>
where t is TextBox
&& t.Name.StartsWith("sum")
select t).Cast<TextBox>().ToArray();
Thanks to Thorsten this is what I ended up with:
string string1;
string string2;
string string3;
private void sumX()
{
for (int i = 1; i < 31; i++)
{
string1 = "br" + i + "txt" + '1';
string2 = "br" + i + "txt" + '2';
string3 = "sumTxt" + i;
TextBox s = (TextBox)this.Controls[string3];
TextBox b1 = (TextBox)this.Controls[string1];
TextBox b2 = (TextBox)this.Controls[string2];
decimal sum = Decimal.Parse(b1.Text) + Decimal.Parse(b2.Text);
s.Text = sum.ToString();
}