|
-
Apr 26th, 2013, 05:48 AM
#1
Thread Starter
Frenzied Member
[RESOLVED] Insert at a line
If I have a string that has many lines in it, is it possible to insert a string at a certain line? I see that there is an insert function for strings. Is there a function to insert a string at a certain line of another string?
-
Apr 26th, 2013, 05:55 AM
#2
Re: Insert at a line
You'd have to know exactly where the beginning of the line you wanted to insert before was, which is not that easy. The simplest way is to Split the String on the line breaks, create a List(Of String) from the resultant array, Insert into that List, then use String.Join to join the list items back into a single String.
-
Apr 26th, 2013, 06:10 AM
#3
Thread Starter
Frenzied Member
Re: Insert at a line
I know that you can split a string into an array. Is there an inbuilt way to split a string into a list of string?
-
Apr 26th, 2013, 06:25 AM
#4
Re: Insert at a line
Given that you're also trying to get a certain line of a string as well, it occurs to me that you probably shouldn't be storing it as a single string, but as a list of strings anyway. When you get the string initially, convert it to a List(Of String), and keep it as such whilst you're doing all these manipulations (get/set/insert etc) until you need to display it or write it to file or whatever, and only then convert it back to a single string.
Even better would be to define a class to represent whatever this string ultimately is that exposes the Lines and a method for getting the full string out.
-
Apr 26th, 2013, 06:26 AM
#5
Re: Insert at a line
 Originally Posted by Simon Canning
I know that you can split a string into an array. Is there an inbuilt way to split a string into a list of string?
There is an inbuilt way of converting a String array to a List(Of String) (it's the List(Of T) constructor)
-
Apr 26th, 2013, 06:30 AM
#6
Re: Insert at a line
 Originally Posted by Evil_Giraffe
Even better would be to define a class to represent whatever this string ultimately is that exposes the Lines and a method for getting the full string out.
Probably just a StringCollection and an extension method would be enough.
-
Apr 26th, 2013, 06:41 AM
#7
Thread Starter
Frenzied Member
Re: Insert at a line
Probably just a StringCollection and an extension method would be enough.
Can you please explain how to do this?
-
Apr 26th, 2013, 06:47 AM
#8
Re: Insert at a line
 Originally Posted by Simon Canning
Can you please explain how to do this?
I'm not going to explain anything about the StringCollection class or how to create an extension method because it is very easy to find information on them yourself. As for what the extension method should do:
Code:
Return String.Join(Environment.NewLine, myStringCollection.Cast(Of String)())
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|