Special characters in string.Replace - c#

I want to replace special characters in string.
For example this is input text
http\u00253A\u00252F\u00252Fvideo.l3.fbcdn.net\u00252Fcfs-l3-ash4\u00252F351111\u00252F203\u00252F260478023976707_55781.mp4\u00253Foh\u00253D064626d4996116bdcde2d52f9b70e1f0\u002526oe\u00253D4E566C00\u002526l3s\u00253D20110823082632\u002526l3e\u00253D20110825083632\u002526lh\u00253D0dbcb2d22cd4dd5eb10bf
and then I expect this result :
http://video.l3.fbcdn.net/cfs-l3-ash4/351111...
But string is not replacing as expected
string[] BadCharacters = { "\\u00253A", "\\u00252F", "\\u00253F" };
string[] GoodCharacters = { ":", "/", "?" };
int i;
for (i = 0; i <= 2; i++)
{
textBox2.Text = textBox1.Text.Replace(BadCharacters[i], GoodCharacters[i]);
}

Your problem is your string gets stomped every iteration through the loop by going back to TextBox1.Text, you need to keep it in a local and keep using the changed value for the next substitution:
var changedText = textBox1.Text;
// always modify and assign to temp, that way we modify previous
for (i = 0; i <= 2; i++)
{
changedText = changedText.Replace(BadCharacters[i], GoodCharacters[i]);
}
textBox2.Text = changedText;

Try this:
var tmp = textBox1.Text;
for (i = 0; i <= 2; i++)
{
tmp = tmp.Replace(BadCharacters[i], GoodCharacters[i]);
}
textBox2.Text = tmp;

textBox2.Text will only ever contain one of the substitutions for each loop, so you likely see only the last iteration.
for (i = 0; i <= 2; i++)
{
textBox1.Text = textBox1.Text.Replace(BadCharacters[i], GoodCharacters[i]);
}
would likely provide the full substituted string desired.

You need to save the updated value of string each time you replace a substring. So save initial value of textBox1 to textBox2 and use it during iteration. In this way, you won't lose your updated string value.
textBox2.Text = textBox1.Text;
for(i = 0; i <= 2; i++)
{
textBox2.Text = textBox2.Text.Replace(BadCharacters[i], GoodCharacters[i]);
}
Also, by asssigning initial textBox1 value to textBox2 and using it inside your for loop, you save one assigmant statement.

Related

Problems with reading text and display in textboxs in c#

My intention is using File.ReadAllText to read a text file line by line. After that, I will check each string array if it contains the keyword that I expected, I will take the whole string out and display it into a textbox. So here is my code :
OpenFileDialog fopen = new OpenFileDialog();
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if(fopen.FileName != "")
{
textBox1.Text = fopen.FileName;
string save = fopen.FileName;
string save1 = save.Split('.')[0];
//string readtext = File.ReadAllText(save);
//string[] readtext1 = readtext.Split('\n');
string[] readline = File.ReadAllLines(save);
int lines = readline.Count();
textBox2.Text = readtext;
for (int i = 0; i < lines; i++ )
{
if (readline[i].Contains("CPL"))
{
int len = readline[i].Length;
textBox3.Text = readline[i].Substring(2, len - 4);
textBox3.AppendText(Environment.NewLine);
}
}
The problem is : if the input file look like
<>something<>
<>something1<>
<>something2<>
<>something3CPL<>
<>something4CPL<>
<>something5CPL<>
The output is always just the last string array. (here is something5CPL).
What I expected is
something3CPL
something4CPL
something5CPL
Can anybody tell me what is wrong with my code?
Thank you.
You're assigning (overwriting) the text in the textbox each iteration, so it'll only hold the last value you get from the file:
textBox3.Text = readline[i].Substring(2, len - 4);
Instead, use the same technique (appending) as you did with the Environment.Newline:
textBox3.AppendText(readline[i].Substring(2, len - 4));
This will keep adding the new values onto the end of the textbox's existing text, as you want.
You need to append the text each instead of setting the text in each iteration:
textBox3.AppendText(readline[i].Substring(2, len - 4));
May be in place of
textBox3.Text = readline[i].Substring(2, len - 4);
use
textBox3.Text += readline[i].Substring(2, len - 4);
As a textbox you can't see the results vertically.
Anyway this is the solution:
OpenFileDialog fopen = new OpenFileDialog();
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if(fopen.FileName != "")
{
textBox1.Text = fopen.FileName;
string save = fopen.FileName;
string save1 = save.Split('.')[0];
//string readtext = File.ReadAllText(save);
//string[] readtext1 = readtext.Split('\n');
string[] readline = File.ReadAllLines(save);
int lines = readline.Count();
textBox2.Text = readtext;
for (int i = 0; i < lines; i++ )
{
if (readline[i].Contains("CPL"))
{
int len = readline[i].Length;
textBox3.Text += (readline[i].Substring(2, len - 4) + " ");
}
}

Split string after certain character count

I need some help. I'm writing an error log using text file with exception details. With that I want my stack trace details to be written like the below and not in straight line to avoid the user from scrolling the scroll bar of the note pad or let's say on the 100th character the strings will be written to the next line. I don't know how to achieve that. Thanks in advance.
SAMPLE(THIS IS MY CURRENT OUTPUT ALL IN STRAIGHT LINE)
STACKTRACE:
at stacktraceabcdefghijklmnopqrstuvwxyztacktraceabcdefghijklmnopqrswxyztacktraceabcdefghijk
**MY DESIRED OUTPUT (the string will write to the next line after certain character count)
STACKTRACE:
at stacktraceabcdefghijklmno
pqrstuvwxyztacktraceabcdefgh
ijklmnopqrswxyztacktraceabcd
efghijk
MY CODE
builder.Append(String.Format("STACKTRACE:"));
builder.AppendLine();
builder.Append(logDetails.StackTrace);
Following example splits 10 characters per line, you can change as you like {N} where N can be any number.
var input = "stacktraceabcdefghijklmnopqrstuvwxyztacktraceabcdefghijklmnopqrswxyztacktraceabcdefghijk";
var regex = new Regex(#".{10}");
string result = regex.Replace(input, "$&" + Environment.NewLine);
Console.WriteLine(result);
Here is the Demo
you can use the following code:
string yourstring;
StringBuilder sb = new StringBuilder();
for(int i=0;i<yourstring.length;++i){
if(i%100==0){
sb.AppendLine();
}
sb.Append(yourstring[i]);
}
you may create a function for this
string splitat(string line, int charcount)
{
string toren = "";
if (charcount>=line.Length)
{
return line;
}
int totalchars = line.Length;
int loopcnt = totalchars / charcount;
int appended = 0;
for (int i = 0; i < loopcnt; i++)
{
toren += line.Substring(appended, charcount) + Environment.NewLine;
appended += charcount;
int left = totalchars - appended;
if (left>0)
{
if (left>charcount)
{
continue;
}
else
{
toren += line.Substring(appended, left) + Environment.NewLine;
}
}
}
return toren;
}
Best , Easiest and Generic Answer :). Just set the value of splitAt to the that number of character count after that u want it to break.
string originalString = "1111222233334444";
List<string> test = new List<string>();
int splitAt = 4; // change 4 with the size of strings you want.
for (int i = 0; i < originalString.Length; i = i + splitAt)
{
if (originalString.Length - i >= splitAt)
test.Add(originalString.Substring(i, splitAt));
else
test.Add(originalString.Substring(i,((originalString.Length - i))));
}

Moving in text file with C#

I have a problem with C#.
I am writing code to search a text file until it finds a certain word, then the code should move three lines and read the fourth, then continue the search to find the certain word again.
Now I don't know how to navigate through the file (forward and backward) to the line I want.
Can anybody help?
You can do something like this:
var text = File.ReadAllLines("path"); //read all lines into an array
var foundFirstTime = false;
for (int i = 0; i < text.Length; i++)
{
//Find the word the first time
if(!foundFirstTime && text[i].Contains("word"))
{
//Skip 3 lines - and continue
i = Math.Min(i+3, text.Length-1);
foundFirstTime = true;
}
if(foundFirstTime && text[i].Contains("word"))
{
//Do whatever!
}
}
// read file
List<string> query = (from lines in File.ReadLines(this.Location.FullName, System.Text.Encoding.UTF8)
select lines).ToList<string>();
for (int i = 0; i < query.Count; i++)
{
if (query[i].Contains("TextYouWant"))
{
i = i + 3;
}
}
Your requirements state that you are searching for a specific word. If that is true and you are not instead looking for a specific string, then the checked answer on this is wrong. Instead you should use:
string[] lines = System.IO.File.ReadAllLines("File.txt");
int skip = 3;
string word = "foo";
string pattern = string.Format("\\b{0}\\b", word);
for (int i = 0; i < lines.Count(); i++)
{
var match = System.Text.RegularExpressions.Regex.IsMatch(lines[i], pattern);
System.Diagnostics.Debug.Print(string.Format("Line {0}: {1}", Array.IndexOf(lines, lines[i], i) + 1, match));
if (match) i += skip;
}
If you use the string.contains method and the word you are searching for is "man", while your text somewhere contains "mantle" and "manual", the string.contains method will return as true.

c# How to read and write from multiline textBox line by line?

I have a simple program it has a function to read a line from multiline textBox when i press a button
what i made to do that is this code :
TextReader read = new System.IO.StringReader(textBox1.Text);
int rows = 100;
string[] text1 = new string[rows];
for (int r = 1; r < rows; r++)
{
text1[r] = read.ReadLine();
}
so when click button1 it the code will be like this:
textBox2=text1[1];
[1] mean the first line How can i do it automaticaly by one click ?
or with one click the first line to textBox2
the second to textBox3 .....ect..
plz i want the code and where i should put it ^_^
or if there is another way to do that
The property Lines is there for you
if(textBox1.Lines.Length > 0)
textBox2.Text=textBox1.Lines[0];
or, put your textboxes ordered in a temporary array and loop on them (of course we should always check the number of lines present in textBox1)
TextBox[] text = new TextBox[] {textBox2, textBox3, textBox4};
if(textBox.Lines.Length >= 3)
{
for(int x = 0; x < 3; x++)
text[x] = textBox1.Lines[x];
}
Simple programming read and write a one-by-one line from multiline textBox in C#
Write line one-by-one:
textbox1.AppendText("11111111+");
textbox1.AppendText("\r\n222222222");
textbox1.AppendText("\r\n333333333");
textbox1.AppendText("\r\n444444444");
textbox1.AppendText("\r\n555555555");
Read line one-by-one:
for (int i = 0; i < textbox1.Lines.Length; i++)
{
textbox2.Text += textbox1.Lines[i] + "\r\n";
}
You can use following snippet for reading comma separated and newline separated values from multiline textbox -
if (!string.IsNullOrEmpty(Convert.ToString(txtBoxId.Text)))
{
string IdOrder = Convert.ToString(txtBoxId.Text.Trim());
//replacing "enter" i.e. "\n" by ","
string temp = IdOrder.Replace("\r\n", ",");
string[] ArrIdOrders = Regex.Split(temp, ",");
for (int i = 0; i < ArrIdOrders.Length; i++)
{
//your code
}
}
I Hope this would help you.

What's wrong with my C# For Loop and If statement?

int LetterCount = 0;
string strText = "Debugging";
string letter;
for (int i = 0; i <strText.Length; i++)
{
letter = strText.Substring(0, 9);
if(letter == "g")
{
LetterCount++;
textBox1.Text = "g appears " + LetterCount + " times";
}
}
So, I'm doing this tutorial thing, and I've been stuck on this exercise for like 4 hours. And I can't figure out what's wrong with my For Loop.
The point of the exercise is to make my program thing tell me how many g's are in the word debugging. But you probably figured that out. Anyway, I'm not even sure that I have the right code for telling me that, because I think that I need to change the second part of the For Loop (the i < ) part.
But my problem is that it isn't registering the "if letter == "g" " at all. Because according to my locals window it says that letter=Debugging, which would make me think that g should be registering on my program 24 times, I think (because str.length is 9 letters long?) But it's registering as 0 no matter what I do.
You are extracting a string of 9 characters. It will never be equal to "g" (which only has one). Here's how I'd do it.
int count = 0;
foreach (char c in strText)
{
if (c == 'g')
count++;
}
Using the for loop:
for (int i = 0; i < strText.Length; i++)
{
if (strText[i] == 'g')
count++;
}
Take a look at the documentation for string.Substring(x, y).
Basically:
letter = strText.Substring(0, 9);
Isn't giving you a letter. Each time through it's giving you all 9 characters of the string strText. You might want to consider using the variable i for one of the values you pass to Substring.
(I've deliberately not given you the entire answer as you seem to want to understand, so, if the pointers I've given don't get you there, let me know and I'll expand my answer =)
Try this:
for (int i = 0; i <strText.Length; i++)
{
if(strText[i] == 'g')
{
LetterCount++;
}
}
textBox1.Text = "g appears " + LetterCount + " times";
The issue is that you are looking at the entire string when you compare to "g". By specifying an index you are telling it to look at a specific character in the string. Also, I removed your substring because it did not appear to be doing anything.
You're not using i at all in your for loop.
Do you mean
letter = strText.Substring(i, 1);
?
Well, you are taking substring that is long 9 charachters and comparing it to "g". It won't be equal.
You should try:
letter = strText.Substring(i,1);
Because String.Substring(int, int) takes two arguments: the offset and amount to take.
In your case, letter = strText.Substring(0, 9); will simply assign letter's value to "Debugging". If you want to check each letter individually, you need to write letter = strText.Substring(i, 1).
You're probably looking for something like this:
int LetterCount = 0;
string strText = "Debugging";
string letter;
for (int i = 0; i <strText.Length; i++)
{
letter = strText.Substring(i, 1);
if(letter == "g")
{
LetterCount++;
textBox1.Text = "g appears " + LetterCount + " times";
}
}
letter = strText.Substring(0, 9);
at this point, 'letter' has the value "Debugging" since you're taking the entire string.
Try letter = strText[i] so you isolate the single letter.
What #Rob said.
Try something like this:
int gCount = 0;
string s = "Debugging";
for ( int i = 0; i <strText.Length; i++)
{
if ( s[i] == 'g' ) ++gCount ;
}
textBox1.Text = "g appears " + gCount+ " times";
namespace runtime
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int lettercount = 0;
string strText = "Debugging";
string letter;
for (int i = 0; i < strText.Length; i++)
{
letter = strText.Substring(i,1);
if (letter == "g")
{
lettercount++;
}
}
textBox1.Text = "g appear " + lettercount + " times";
}
}
}

Categories

Resources