How can I replace each new line with a auto-incremented number? - c#

I am lookind for a effective way that I can replace newlines with an auto-incrementing number.
eg.
this is line 1
this is line 2
this is line 3
this is line 4
to
1. this is line 1
2. this is line 2
3. this is line 3
4. this is line 4
Is looping through each line the only way? I guess thats the way I will implement it for now. Unless I find a better way here :) Just some pseudo code will do. But I am using C#

This is probably easier if you use a shell command, for example:
nl -ba -s'. ' -w1

Just some pseudo code will do.
int lineNo=1;
for(String str:listOfString){
System.out.println(lineNo + " : " + str);
lineNo++;
}
Note: code provided is written in java , You can get the basic idea from that

You can use LINQ:
string[] lines = ...
string newText = string.Concat(lines.Select(
(line, index) => string.Format("{0}. {1}", index, line)));

Related

Getting a part of a string and outputting it to another string

Hi so i'm not exactly sure if the title justifies this question I'm not too good at phrasing sorry.
But what i'm trying to do is um like:
String joggingResults = ",Distance: 2.4km, Duration: 14minutes,";
And ideally, I would like to search joggingResults for " , " and output the words beside it.. and stops when it finds another " , " ... Does this make any sense? haha
My expected result would be something like this but each line is on a new string:
Distance: 2.4km
Duration: 14minutes
I hope someone helps me out tysm
You can split using ',' and then loop through the array and display the results.
var results = joggingResults.Split(',');
foreach(var item in results)
{
Console.WriteLine(item);
}
Note:- Assuming it is a console application. You can display it as per your type of application.
joggingResults.Split(',')
Will give you a collection of strings split where the commas are.

Remove a linebreak in c#

I have the following lines of text:
W&BL 15&384&320&214&1&S235JR&&&&&&&&&&S&&0.267&&&&4&&
N&214.nc
A&214&1&&15
W&BL 15&384&320&215&1&S235JR&&&&&&&&&&S&&0.267&&&&4&&
N&215.nc
A&213&2&&14
I want to remove the linebreaks so the outcome will be like this:
A&213&2&&14W&BL 15&384&320&214&1&S235JR&&&&&&&&&&S&&0.267&&&&4&&N&214.nc
A&214&1&&15W&BL 15&384&320&215&1&S235JR&&&&&&&&&&S&&0.267&&&&4&&N&215.nc
I do this because I need to format these lines and I'm putting the whole textfile in a reader per line. When I filter this with linebreaks I can't properly search through the lines. Since I need to delete everything after the S235JR, replace the & with ; and start the line with the BL code.
If someone knows a smarter/better solution to filter these lines, you will be my hero of the day.
Edit for clarification:
This is a example and how it needs to be formatted:
H&HEA100&1712&&1001&2&S235JR&&&HEA100 - 1712&&&&&&&S&&0.96&&&&2&&&1.7&0.2&0.2
N&1001.nc
W&BL 15&384&320&215&1&S235JR&&&&&&&&&&S&&0.267&&&&4&&
N&215.ncA&214&1&&15
H&L80X8&375&&1010&1&S275JR&&&L80X8 - 375&&&&&&&S&&0.117&&&&4&&&0.4&0.1&0.1
N&1010.nc
After formatting:
H;HEA100;1712;;1001;2;S235JR;
BL 15;384;320;215;1;S235JR;
L80X8;375;;1010;1;S275JR;
The input is a text file imported with a StreamReader. The H, BL 15 and L80X8 are determined after 6 & characters. The program was originally written in DOS and I need to convert it into C#. I'm sorry for the confusion.
x.Replace(Environment.NewLine, String.Empty);
where x is string.
From the example in your question, it looks like you want to remove line breaks, but keep every third line break.
You can use a regular expression that matches three lines, and remove the two line breaks between them:
text = Regex.Replace(text, #"(.+)\r\n(.+)\r\n(.+)", "$1$2$3");
x = x.Replace("\r\n", "");
x is your string Object;
string x = x.Replace("&", ";");
string x1 = x.Substring(x.IndexOf("H;"), x.IndexOf("S235JR;", x.IndexOf("H;")) - x.IndexOf("H;")+7);
string x2 = x.Substring(x.IndexOf("BL 15;"), x.IndexOf("S235JR;", x.IndexOf("BL 15;")) - x.IndexOf("BL 15;")+7);
string x3 = x.Substring(x.IndexOf("L80X8;"), x.IndexOf("S275JR;", x.IndexOf("L80X8;")) - x.IndexOf("L80X8;")+7);
string result = x1 + "\r\n" + x2 + "\r\n" + x3;

Find index of first Char(Letter) in string

I have a mental block and can't seem to figure this out, sure its pretty easy 0_o
I have the following string: "5555S1"
String can contain any number of digits, followed by a Letter(A-Z), followed by numbers again.
How do I get the index of the Letter(S), so that I can substring so get everything following the Letter
Ie: 5555S1
Should return S1
Cheers
You could also check if the integer representation of the character is >= 65 && <=90.
Simple Python:
test = '5555Z187456764587368457638'
for i in range(0,len(test)):
if test[i].isalpha():
break
print test[i:]
Yields: Z187456764587368457638
Given that you didn't say what language your using I'm going to pick the one I want to answer in - c#
String.Index see http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx for more
for good measure here it is in java string.indexOf
One way could be to loop through the string untill you find a letter.
while(! isAlpha(s[i])
i++;
or something should work.
This doesn't answer your question but it does solve your problem.
(Although you can use it to work out the index)
Your problem is a good candidate for Regular Expressions (regex)
Here is one I prepared earlier:
String code = "1234A0987";
//timeout optional but needed for security (so bad guys dont overload your server)
TimeSpan timeout = TimeSpan.FromMilliseconds(150);
//Magic here:
//Pattern == (Block of 1 or more numbers)(block of 1 or more not numbers)(Block of 1 or more numbers)
String regexPattern = #"^(?<firstNum>\d+)(?<notNumber>\D+)(?<SecondNum>\d+)?";
Regex r = new Regex(regexPattern, RegexOptions.None, timeout);
Match m = r.Match(code);
if (m.Success)//We got a match!
{
Console.WriteLine ("SecondNumber: {0}",r.Match(code).Result("${SecondNum}"));
Console.WriteLine("All data (formatted): {0}",r.Match(code).Result("${firstNum}-${notNumber}-${SecondNum}"));
Console.WriteLine("Offset length (not that you need it now): {0}", r.Match(code).Result("${firstNum}").Length);
}
Output:
SecondNumber: 0987
All data (formatted): 1234-A-0987
Offset length (not that you need it now): 4
Further info on this example here.
So there you go you can even work out what that index was.
Regex cheat sheet

C# : Printing variables and text in a textbox

I need to know the command that I can print a sentence like "the item Peter at row 233 and column 1222 is not a number " .
I far as now I have made this:
string[] lineItems = (string[])List[]
if (!Regex.IsMatch(lineItems[0], (#"^\d*$")))
textBox2.Text += " The number ,lineItems[0], is bigger than
10 " + Environment.NewLine;
I want to print the array fields that have error. So if it finds something it will print it.
I made a code that correctly prints that there is an error on this line of the array, but I cant print the item of the array.
I need to have an Environment.NewLine because I will print many lines.
Thanks ,
George.
foreach (int lineNumber in lineItems)
{
if (lineNumber > 10)
textBox2.Text += "The number " + lineNumber + " is bigger than 10\n";
}
Something like this should work, (I have not checked the c# code, I am working on a mac at the moment)
TextBox2.Text="This is FirstLine\nThis is Second Line";
The code is not compilable absolutely, but I may be understand what you're asking about.
If you are asking about how to compose the string of text box, by adding new strings to it, based on some desicional condition (regex), you can do folowing, pseudocode:
StringBuilder sb = new StringBuidler();
if (!Regex.IsMatch(lineItems[i], (#"^\d*$")))
sb.Append(string.Format(The number ,{0}, is bigger than 10, lineItems[i]) + Environment.NewLine);
textBox2.Text = sb.ToString();
If this is not what you want, just leave the comment, cause it's not very clear from post.
Regards.

Splitting a CSV and excluding commas within elements

I've got a CSV string an I want to separate it into an array. However the CSV is a mix of strings and numbers where the strings are enclosed in quotes and may contain commas.
For example, I might have a CSV as follows:
1,"Hello",2,"World",3,"Hello, World"
I would like it so the string is split into:
1
"Hello"
2
"World"
3
"Hello, World"
If I use String.Split(','); I get:
1
"Hello"
2
"World"
3
"Hello
World"
Is there an easy way of doing this? A library that is already written or do I have to parse the string character by character?
The "A Fast CSV Reader" article on Code Project. I've used it happily many times.
String.Split() is icky for this. Not only does it have nasty corner cases where it doesn't work like the one you just found (and others you haven't seen yet), but performance is less than ideal as well. The FastCSVReader posted by others will work, there's a decent csv parser built into the framework (Microsoft.VisualBasic.TextFieldParser), and I have a simple parser that behaves correctly posted to this question.
I would suggest using one of the following solutions, was just testing a few of them (hence the delay):-
Regex matching commas not found within an enclosing double aprostophe
A Fast CSV Reader - for read CSV only
FileHelpers Library 2.0 - for read/write CSV
Hope this helps.
It's not the most elegant solution, but the quickest if you want to just quickly copy and paste code (avoiding having to import DLLs or other code libraries):
private string[] splitQuoted(string line, char delimeter)
{
string[] array;
List<string> list = new List<string>();
do
{
if (line.StartsWith("\""))
{
line = line.Substring(1);
int idx = line.IndexOf("\"");
while (line.IndexOf("\"", idx) == line.IndexOf("\"\"", idx))
{
idx = line.IndexOf("\"\"", idx) + 2;
}
idx = line.IndexOf("\"", idx);
list.Add(line.Substring(0, idx));
line = line.Substring(idx + 2);
}
else
{
list.Add(line.Substring(0, Math.Max(line.IndexOf(delimeter), 0)));
line = line.Substring(line.IndexOf(delimeter) + 1);
}
}
while (line.IndexOf(delimeter) != -1);
list.Add(line);
array = new string[list.Count];
list.CopyTo(array);
return array;
}

Categories