StreamReader text = new StreamReader(#textBox1.Text.ToString());
String tempArray = text.ReadToEnd();
char[] charA = tempArray.ToCharArray();
Console.Write(charA);
output is like that
****4****
**26*71**
871***694
*6*****4*
2*59*67*8
*8*****2*
658***471
**94*85**
****7****
but ı want to write and save 1d array on 1 row simple ;
****4****
26*71
871***694
*6*****4*
2*59*67*8
*8*****2*
658***471
94*85
****7****
how can ı split this ?
There's a lot going on in the code you've shared:
StreamReader text = new StreamReader(#textBox1.Text.ToString());
String tempArray = text.ReadToEnd();
char[] charA = tempArray.ToCharArray();
Console.Write(charA);
textBox1.Text already is a string, so you don't need the .ToString() behind that.
By the way you don't need to prefix a field with a # unless it's the field has the same name as a keyword. You're free to do it anyway if you like, though).
StreamReader text = new StreamReader(textBox1.Text);
String tempArray = text.ReadToEnd();
char[] charA = tempArray.ToCharArray();
Console.Write(charA);
Next, if all you want to do with the file is read all its contents as a string, you might want to use File.ReadAllText() as it doesn't keep the file open:
String tempArray = File.ReadAllText(textBox1.Text);
char[] charA = tempArray.ToCharArray();
Console.Write(charA);
The console outputs multiple lines but the char[] still really is a 1D array. The problem is that there are newline characters in the file, which get processed by the console.
If you want to remove these newlines, it's easier to do so while you're still working with a string - because there are quite a few built-in features for this. Someone already commented using string.Replace("\r\n", "") to do this trick:
String tempArray = File.ReadAllText(textBox1.Text);
tempArray = tempArray.Replace("\r", "");
tempArray = tempArray.Replace("\n", "");
char[] charA = tempArray.ToCharArray();
Console.Write(charA);
Related
I have file contains two lines and each line contains 200 fields and I would like to split it into arrays
using (StreamReader sr = File.OpenText(pathSensorsCalc))
{
string s = String.Empty;
while ((s = sr.ReadLine()) == null) { };
String line1 = sr.ReadToEnd();
String line2 = sr.ReadToEnd();
CalcValue[0] = new String[200];
CalcValue[1] = new String[200];
CalcValue[0] = line1.Split(' ');
CalcValue[1] = line2.Split(' ');
}
After the code above, CalcValue[1] is empty and CalcValue[0] contains data of the second line (instad of the first one). Any ideas?
When using
sr.ReadToEnd()
, you are reading to the end of your input stream. That means, after the first call of
String line1 = sr.ReadToEnd()
your stream is already at the last position. Replace your ReadToEnd() call with ReadLine() calls. That should work.
In the Windows OS, a new line is represented by \r\n. So you should not split the lines by spaces (" ").
Which means you should use another overload of the Split method - Split(char[], StringSplitOptions). The first argument is the characters you want to split by and the second is the options. Why do you need the options? Because if you split by 2 continuous characters you get an empty element.
So now it is easy to understand what this code does and why:
line1.Split (new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
I have a text file with this multi line structure:
12345 beautiful text in line01
95469 other text in line02
16987 nice text in line03
(etc...)
and want this:
12345
beautiful text in line01
95469
other text in line02
16987
nice text in line03
So, for every line, at position 5 i need a new line for the textual string.
Tried inserting \n with string.Remove().Insert() but works only for first line.
How can I do this?
EDIT
Code added by request
In input.txt there is the multiline textfile.
StreamReader myReader = new StreamReader("input.txt");
string myString00 = myReader.ReadLine();
string myStringFinal = myString00;
myStringFinal = myStringFinal.Remove(5, 1).Insert(5, "\n");
myReader.Close();
FileStream myFs = new FileStream("output.txt", FileMode.Create);
// First, save the standard output.
TextWriter tmp = Console.Out;
StreamWriter mySw = new StreamWriter(myFs);
Console.SetOut(mySw);
Console.WriteLine(myStringFinal);
Console.SetOut(tmp);
Console.WriteLine(myStringFinal);
mySw.Close();
Console.ReadLine();
Here is something you can try with a Regex
var subject = #"12345 beautiful text in line01
95469 other text in line02
16987 nice text in line03";
var expected = Regex.Replace(subject,#"(\d{5})\s?","$1\r\n");
Basically this finds 5 digits followed by a space(optional), if found replaces it with digits and a new line. And you're done.
This will work only if the number is exactly 5 characters.
string input = #"12345 beautiful text in line01
95469 other text in line02
16987 nice text in line03";
var lines = input.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var formattedLines = lines
.Select(x => new
{
Number = int.Parse(x.Substring(0, 5)),
Data = x.Substring(5).TrimStart()
})
.ToList();
formattedLines will be a collection of your lines, with Number and Data holding the info from the lines.
var firstLinesData = formattedLines[0].Data;
So now, to make your output format:
StringBuilder builder = new StringBuilder();
foreach (var item in formattedLines)
{
builder.AppendLine(item.Number.ToString());
builder.AppendLine(item.Data);
}
string output = builder.ToString();
loop over each line. Use substring (http://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx) to get the first 5 character as a string. Use a string builder and add the first part, grab the next part and add tot he string builder
I have a file text which splited by newline character. the text file such this:
merah.dc
kuning.dc
hijau.dc
biru.dc
orange.dc
mahopermanent.dc
I want to count them by splitting with a newline character. so, the count of them are 6. I could only do this with looping:
int count = 0;
string path = "directory\\admin.txt";
StreamReader moco = File.OpenText(path);
string s;
while ((s = moco.ReadLine())!= null)
{
count++;
}
I want to count them with a simple way like the PHP syntax:
<?php
$file = file("directory\\admin.txt");
$count = count($file);
echo $count;
?>
The above syntax able to counts them without looping. Just use file() and count(). is any function in C# which equals with that function ?
You can use ReadLines without loading whole file into the memory (of course this method can be useful if your file is large)
int count = File.ReadLines(filename).Count();
Step 1 : You can use ReadAllLines() function to get all Lines from the given file path as a String Array.
Step 2: you can invoke Length property on the obtained String Array to get the Count of Total Lines
Try This:
using System.IO;
String [] allLines=File.ReadAllLines(#"directory\admin.txt");
int length=allLines.Length;
You don't need to split them by a new character, use File.ReadAllLines (which returns an array of strins, each element is a line).
int lineCount = File.ReadAllLines("test.txt").Length;
If you want to use split, then:
int lineCount = File.ReadAllText("test.txt").Split('\n').Count();
ReadAllText returns a strin with the entire content of the file.
int count = File.ReadAllLines(#"directory\\admin.txt").Length;
You can Split() the textfile
StreamReader moco = File.OpenText(path);
string s;
string splitArray[] = s.Split('\n'); //Split on newline
int length = splitArray[].Length;
I tried to split a string wich contains these character #
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
but every time the array contains just one member. I've tried a lot of combinations but anything seems to work, I also tried to replace the string with a blank space and it kinda works - the problem is that it remains a single string.
domicilio = domicilio.Replace(#"#", #" ");
How can I resolve this?
Complete code:
String[] domicilioSeparado;
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
If you just want to split a string on a delimiter, in this instance '#', then you can use this:
domicilioSeparado = domicilio.Split("#");
That should give you what you want. Your second attempt simply replaces all the characters '#' in the string with ' ', which doesn't seem to be what you want. Can we see the string you're trying to split? That might help explain why it's not working.
EDIT:
Ok, here's how I think your code should look, give this a shot and let me know how it goes.
List<string> domicilioSeparado = new List<string>();
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split("#");
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
Try this:
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
Some notes:
1 - It is ('#'), instead of ("#"); 2 - Replace does not split a string, it only replace that part, keeping as a single string.
In case you want an example that includes the printing of the whole array:
string domicilio = "abc#def#ghi";
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
for (int i = 0; i < domicilioSeparado.Length; i++)
{
MessageBox.Show(domicilioSeparado[i]);
}
It will open a Message Box for each element within domicilioSeparado.
I´ve got a text file with tabulator separated data. What I need in my C# application is that I read one line from the text file and save them to an array, separate them at the each \t. Then I do the same thing with the next row.
My code:
StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();
Now, I already tried to write the line into an array but that doesn´t work. Does anyone one how to manage this?
Use the Split method to create an Array of the line
string[] parts = s.Split('\t');
See Documentation on Split() here
foreach (string line in System.IO.File.ReadAllLines(dlg.FileName))
{
var myArray = line.Split('\t');
}
s.Split('\t') will split your string by the tabulator character, and create a string[] with appropriate length.
Ammending your example code:
StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();
var items = s.Split('\t');
In the end, items contains an array of strings that represent the characters between the tabs. The tabs are not included in the array. The array may contain empty elements (for the case of two consecutive tabs).
Use the String.Split() method: http://msdn.microsoft.com/en-us/library/b873y76a.aspx
StreamReader reader = new StreamReader("input.txt");
string[] content = reader.ReadToEnd().Replace("\n","").Split('\t');
if you want to keep New Line's than
string[] content = reader.ReadToEnd().Split('\t');
In the example below, items will be a String[] containing each line of text's values. It will be overwritten with each iteration so you'll want to do something with it inside the loop. Save it to a larger collection, write it to a file, etc...
StreamReader sr = new StreamReader(dlg.FileName);
while (sr.Peek() >= 0) {
var line = sr.ReadLine();
var items = line.Split(new Char[] { '\t' });
}
If the file contains only one line, then use:
string[] myArray = s.Split('\t');