How do cut line using C#? - c#

How do cut the following line?
19 02 2000 01:53:36 System Line [**12345**] ----> filename.txt
I need output to be
12345
Could you help me?

var result = myString.Split(new char[] { '[', ']' } )[1];
should do it.

Related

Regex if condition c#

Text from txt file:
10 25
32 44
56 88
102 127
135 145
...
If it is a first line place 0, rest use the last number as a first in new line. Is it possible to do it or I need to loop through lines after regex parse.
0 10 25
25 32 44
44 56 88
88 102 127
127 135 145
(?<Middle>\d+)\s(?<End>\d+) //(?<Start>...)
I would advise against using regex for readability reasons but this will work:
var input = ReadFromFile();
var regex = #"(?<num>\d*)[\n\r]+";
var replace = "${num}\n${num} ";
var output = Regex.Replace(input, regex, replace);
That will do everything apart from the first 0.
Note that a regex approach does not sound quite good for a task like this. It can be used for small input strings, for larger ones, it is recommended that you write some more logic and parse text line by line.
So, more from academic interest, here is a regex solution showing how to replace with different replacement patterns based on whether the line matched is first or not:
var pat = #"(?m)(?:(\A)|^(?!\A))(.*\b\s+(\d+)\r?\n)";
var s = "10 25\n32 44\n56 88\n102 127\n135 14510 25\n32 44\n56 88\n102 127\n135 145";
var res = Regex.Replace(s, pat, m => m.Groups[1].Success ?
$"0 {m.Groups[2].Value}{m.Groups[3].Value} " : $"{m.Groups[2].Value}{m.Groups[3].Value} ");
Result of the C# demo:
0 10 25
25 32 44
44 56 88
88 102 127
127 135 14510 25
25 32 44
44 56 88
88 102 127
127 135 145
Note the \n line breaks are hardcoded, but it is still just an illustration of regex capabilities.
Pattern details
(?m) - an inline RegexOptions.Multiline modifier
(?:(\A)|^(?!\A)) - a non-capturing group matching either
(\A) - start of string capturing it to Group 1
| - or
^(?!\A) - start of a line (but not string due to the (?!\A) negative lookahead)
(.*\b\s+(\d+)\r?\n) - Group 2:
.*\b - 0+ chars other than newline up to the last word boundary on a line followed with...
\s+ - 1+ whitespaces (may be replaced with [\p{Zs}\t]+ to only match horizontal whitespaces)
(\d+) - Group 3: one or more digits
\r?\n - a CRLF or LF line break.
The replacement logic is inside the match evaluator: if Group 1 matched (m.Groups[1].Success ?) replace with 0 and Group 2 + Group 3 values + space. Else, replace with Group 2 + Group 3 + space.
With C#.
var lines = File.ReadLines(fileName);
var st = new StringBuilder(); //or StreamWriter directly to disk ect.
var last = "0";
foreach (var line in lines)
{
st.AppendLine(last + " " + line );
last = line.Split().LastOrDefault();
}
var lines2 = st.ToString();

split string to three doubles

I used C# and I would like split text comprised 3 doubles seperated by commas and spaces.
I did:
double[] doubles = mystr.Trim().Split(new char[] { ' ', ',' })
.Select(s => Convert.ToDouble(s))
.ToArray();
when mystr = 33,44,55 for example it works fine (numbers seperated by only one comma)
Also, when mystr= 33 44 55 for example it works fine (numbers seperated by only one space)
BUT, when mystr= 33, 44, 55 it doesn't works (one space after the comma between each two numbers)
It also doesn't work when mystr = 33 44 55 (two spaces between each two numbers)
In both above examples I got an unhandled exception.
How can I solve it?
Thanks!
You can add an option to remove empty entries in the Split:
var array = Array.ConvertAll(mystr.Split(new [] { ' ', ',' },
StringSplitOptions.RemoveEmptyEntries),
Convert.ToDouble);
You could use System.Text.RegularExpressions.Regex:
var pattern = #"(\d+)((,\s*|\s+)|$)";
const int RegexTimeoutSeconds = 1;
var matches = Regex.Matches(mystr, pattern, RegexOptions.None, TimeSpan.FromSeconds(RegexTimeoutSeconds));
var doubles = new List<double>();
foreach (Match match in matches)
{
var group = match.Groups[1];
var d = Convert.ToDouble(group.Value);
doubles.Add(d);
}
Just try specifying StringSplitOptions, and use StringSplitOptions.RemoveEmptyEntries to remove empty strings..
double[] doubles = mystr.Trim().Split(new char[] { ' ', ',' },StringSplitOptions.RemoveEmptyEntries)
.Select(Convert.ToDouble)
.ToArray();

How to split string with 1-many spaces and place words in an array

As the title says,
How do i split a string with 1-* numbers of spaces, and place each word in an array
right now I am using Split(' ') it works with single spaces, but when it comes to multiple spaces it causes an issue
Here is my sample string:
0x886fe248 ElanTPCfg.exe 1132 2492 0 -------- 1 0 2014-01-20 09:31:10 2014-01-20 09:31:10
In this example I was only able to get the hexidecimal digit and the executable name, while the others are not read at all
void Main()
{
string s = "0x886fe248 ElanTPCfg.exe 1132 2492 0 -------- 1 0 2014-01-20 09:31:10 2014-01-20 09:31:10";
Console.WriteLine (s.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries));
}
Produces:
You can use StringSplitOptions.RemoveEmptyEntries
var output = input.Split(new [] { " " }, StringSplitOptions.RemoveEmptyEntries);
You can also use Regex.Split:
string s = #"x886fe248 ElanTPCfg.exe 1132 2492 0 -------- 1 0 2014-01-20 09:31:10 2014-01-20 09:31:10";
string[] strArr = Regex.Split(s, #"\s+");
\s+ is one or more whitespace character(s).

Remove spaces in the string array

I have a text file that contains numbers in this format :
84 152 100
86 149 101
83 149 99
86 142 101
How can I remove the spaces and bring it in this shape :
84 152 100
86 149 101
83 149 99
86 142 101
This is what I have tried so far :
string path = Directory.GetCurrentDirectory();
string[] lines = System.IO.File.ReadAllLines(#"data_1_2.txt");
string[] line = lines[0].Trim().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
But the result of this input is :
84
152
100
Use a bit of LINQ magic:
lines = lines.Select(l => String.Join(" ", l.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))).ToArray();
It will split each line using space as a separator, remove empty entries and join them back using space as a separator again.
You can use a simple regular expression:
lines = lines.Select(line => Regex.Replace(line, #"\s+", " ")).ToArray();

C#: splitting a string and not returning empty string

I have a string:
a = "1;2;3;"
And I would like to split it this way:
foreach (string b in a.split(';'))
How can I make sure that I return only 1, 2, 3 and not an 'empty string'?
If I split 1;2;3 then I will get what I want. But if I split 1;2;3; then I get an extra 'empty string'. I have taken suggestions and done this:
string[] batchstring = batch_idTextBox.Text.Split(';', StringSplitOptions.RemoveEmptyEntries);
However, I am getting these errors:
Error 1 The best overloaded method match for 'string.Split(params
char[])' has some invalid arguments C:\Documents and
Settings\agordon\My Documents\Visual Studio
2008\Projects\lomdb\EnterData\DataEntry\DAL.cs 18 36 EnterData
Error 2 Argument '2': cannot convert from 'System.StringSplitOptions'
to 'char' C:\Documents and Settings\agordon\My Documents\Visual Studio
2008\Projects\lomdb\EnterData\DataEntry\DAL.cs 18 68 EnterData
String.Split takes an array when including any StringSplitOptions:
string[] batchstring = batch_idTextBox.Text.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
If you don't need options, the syntax becomes easier:
string[] batchstring = batch_idTextBox.Text.Split(';');
Use StringSplitOptions.
a.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
Pass StringSplitOptions.RemoveEmptyEntries to the Split method.
EDIT
The Split method does not have an overload to split by a single character. You need to specify an array of characters.
foo.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
Didn't know about split options. If you didn't have that you could...
a.Split(';').Where(s => s.Length > 0).ToArray();
Give this a shot:
string test = "1;2;3;";
test = String.Join(",", test.TrimEnd((char)59).Split((char)59));
string test = "1;2;3;";
test = String.Join(",", test.TrimEnd(';').Split(';'));
Use
a.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
There are 4 overloads of .Split, two of them don't support StringSplitOptions and use the params format (so you don't need to create an array of splitters), two of them support StringSplitOptions and require an array of char or string.
string line="Hello! Have nice day."
string[] substr = line.Split(new[] {' '}, 2);
Above code will split the line into two substrings based on first space.
substr[0] will have "Hello!"
substr[1] will have "Have nice day.". Here 2 in Split is an integer counter, you can pass any value based on your requirement.

Categories