|
-
September 12th, 2010, 02:19 AM
#1
Question | Remove text from string
I got a string includes text from a .txt file (string s = File.ReadAllText(TextFilePath));
From this string I want to remove all the text that is between the chars "--" and "\r\n".
For example:
Original: "aaaa \r\n -- abcde \r\n aaaa"
New: "aaaa \r\n aaaa"
How can I do it?
-
September 12th, 2010, 04:32 AM
#2
Re: Question | Remove text from string
Code:
int index = s.IndexOf("--");
if( s > 0 )
{
return s.Substring( 0, index ) + Environment.NewLine;
}
else
{
return s;
}
Last edited by BigEd781; September 12th, 2010 at 04:39 AM.
-
September 12th, 2010, 04:36 AM
#3
Re: Question | Remove text from string
You could use String's IndexOf method to find -- and \r\n, then use Substr to remove whatever is inbetween them.
-
September 12th, 2010, 05:24 AM
#4
Re: Question | Remove text from string
I want you to take another look at my example:
what you gave me doesnt answer my problem.
also, what if there is more than one instance of "-- text \r\n"?
-
September 12th, 2010, 01:38 PM
#5
Re: Question | Remove text from string
 Originally Posted by Sarlula
I want you to take another look at my example:
what you gave me doesnt answer my problem.
also, what if there is more than one instance of "-- text \r\n"?
1. Yes it does.
2. Well, if there can be multiple instances of '--' then I guess you should have said that and included it in your example, eh?
Look at String.Split and/or regular expressions.
-
September 16th, 2010, 02:49 PM
#6
Re: Question | Remove text from string
Code:
string Original = "aaaa \r\n -- abcde \r\n aaaa";
string new_string = Original;
int start = 0;
int end = 0;
int len = 0;
do{
start = new_string.IndexOf("--", start);
if(start == -1)
break;
end = new_string.IndexOf("\r\n", start);
if(end == -1)
break;
len = end + 2 - start;
new_string = new_string.Remove(start, len);
} while (new_string.IndexOf("\r\n", start) > 0);
MessageBox.Show(new_string);
Or
Code:
string Original = "aaaa \r\n -- abcde \r\n aaaa";
string new_string = Original;
for (int a = 0; a < Original.Length; )
{
if (a >= Original.Length)
break;
if (a + 2 == Original.Length)
{
new_string += Original.Substring(a, 2);
break;
}
if (Original.Substring(a, 2) == "--" && Original.IndexOf("\r\n", a) > a)
a = Original.IndexOf("\r\n", a) + 2;
else
new_string += Original.Substring(a++, 1);
}
MessageBox.Show(new_string);
I think i prefere the first one.
Regular expressions is probably 10 times easier.
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
|