tags:

views:

83

answers:

3

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#

+2  A: 

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

org.life.java
+4  A: 

This is probably easier if you use a shell command, for example:

nl -ba -s'. ' -w1
Nabb
+1. Are `-ba` options really needed ?
codaddict
@codaddict Blank lines will not be numbered without `-ba`.
Nabb
@Nabb: I see, thanks.
codaddict
A: 

You can use LINQ:

string[] lines = ...

string newText = string.Concat(lines.Select(
                     (line, index) => string.Format("{0}. {1}", index, line)));
Andrew Bezzub
`string.Format("{0}. {1}", index + 1, line)` with +1, the numbering will start from 1 rather than 0 is something I might use. I find the @org.life.java more intuitive still. but still thanks for an alternative C# answer
jiewmeng