Why is this function crashing my program? - c#

I'm new in programming and this is my first project and I'm using C#. Basically I tryed to do a function that insert one more single quote in string that already have a single quote, but this is crashing my program and I don't know why.
The function:
private string CheckSingleQuote(string txt)
{
for (int i = 0; i < txt.Length; i++)
if (txt[i] == '\'')
txt = txt.Insert(i, "'");
return txt;
}
When I click in a specific button, this function is called ten times to set the value of the strings.

You can do String.Replace("'", "''") or if you want to use the for:
private string CheckSingleQuote(string txt)
{
for (int i = 0; i < txt.Length; i++)
if (txt[i] == '\'')
txt = txt.Insert(i++, "'");
return txt;
}
As mjwills said in the comment the i++ is to skip the ' character that you just inserted.

Related

C# doesn't recognize some symbols

I read strings from text file, and among the strings there is one: "15121 ♥☺020 000000/=n531☻".
I use .Contain() method to spot ♥☺☻ symbols in the string, but it doesn't recognize them. For ♥,☺,☻ I also tried \u2665, \u263a, \u263b (as arguments for .Contain()), but none of them were recognized.
Moreover, I copied the string (from console output window) and pasted it into my code to compare symbols one by one.
string s = "15121 ♥☺020 000000/=n531☻"; // the same with "15121 \u2665\u263a020 000000/=n531\u263b"
for (int j = 0; j < s.Length; j++)
{
Console.WriteLine($"{line[j]} == {s[j]}: {line[j].Equals(s[j])}");
}
This is what I got:
What may be wrong and how do I recognize those symbols?
UPDATE: The input file I read strings from is a usual text file, and the strings inside looks like these (txt opened in Notepad):
As you can see, there is THE string among the others.
I don't use any encoding when reading the txt, and to specify how I do read the file and what the line is, here is my code:
string[] lines = File.ReadAllLines(path + target_file_name);
var list = new List<string>(lines);
for (int i = 0; i < list.Count; i++)
{
string line = list[i];
if (line.Length > 21)
{
Console.WriteLine(line);
if (line.Contains("/=n")) //used just to catch THE string
{
var line_b = Encoding.Unicode.GetBytes(line);
Console.WriteLine($"{line_b} : line = {line}");
foreach (byte m in line_b)
{
Console.Write(m + " ");
}
string s = "AAXX 15121 ♥☺020 000000/=n531☻";
Console.WriteLine();
var s_b = Encoding.Unicode.GetBytes(s);
Console.WriteLine($"{s_b} : s = {s}");
foreach (byte n in s_b)
{
Console.Write(n + " ");
}
Console.WriteLine();
for (int j = 0; j < s.Length; j++)
{
Console.WriteLine($"{line[j]} == {s[j]}: {line[j].Equals(s[j])}");
}
}
Reading all the lines from txt and converting them to List is a must for me. Thus, the line is a string line from initial txt file.
I have dumped the bytes of the inout text string var b = Encoding.Unicode.GetBytes(line); and compare with my literal (#pm100), and here is the result. Not quite sure what it does give me:
I'm sorry, I'm not willing to publish my code, and I may not understand some of your suggestions for I'm not very proficient in C# (and coding in general). So I would appreciate any further help as it is, if possible.

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.

Special characters in string.Replace

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.

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