c# replace string with many "x" [duplicate] - c#

This question already has answers here:
Best way to repeat a character in C#
(21 answers)
Closed 1 year ago.
I am writing a windows form app in C#. I have a label with a random word, e.g. "computer". User has to guess what is this word by guessing letter by letter. But word "computer" must be replaced with as many "x" as there is letters in a word, so in this example user should see "xxxxxxxx".
I tried to replace it with regex like this:
private void Form1_Load(object sender, EventArgs e)
{
word.Text = Regex.Replace(word.Text, #"^[a-zA-Z]+$", "x");
}
But it only replace with single "x".
I also tried with for loop, but the result is the same:
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <= word.Text.Length; i++)
{
word.Text = Regex.Replace(word.Text, #"^[a-zA-Z]+$", "x");
}
}

You can create a new string of "x" repeated the number of characters in your word. No need for regexes.
word.Text = new string('x', word.Text.Length);

Approach without RegEx
string wordText = "computer";
wordText = string.Concat(wordText.Select(x => char.IsLetter(x) ? 'x' : x));
if you want to stay with RegEx, replace #"^[a-zA-Z]+$" with "[a-zA-Z]" to match every single character

Try this:
word.Text=String.Join("",word.Text.Select(s=>s='x').ToArray());

Related

Make search terms on richtextbox case insensitive c#

I have a richtextbox that I've added a search and highlight function to but it will only search for exactly what the user types. I know this is because of the MatchCase property but none of the other options seem to do the job. Here is my code:
private void btnSourceSearch_Click(object sender, EventArgs e)
{
int start = 0;
int end = richTextBox1.Text.LastIndexOf(textBox1.Text);
richTextBox1.SelectAll();
richTextBox1.SelectionBackColor = Color.White;
while(start < end)
{
richTextBox1.Find(textBox1.Text, start, richTextBox1.TextLength, RichTextBoxFinds.MatchCase);
richTextBox1.SelectionBackColor = Color.Yellow;
start = richTextBox1.Text.IndexOf(textBox1.Text, start) + 1;
}
}
Any help would be greatly appreciated. It's probably simple but I've been looking at code for a good few hours over the last week and it's beginning to look a lot like the Matrix!
Thanks
I don’t know if you are familiar with regular expressions, but they are useful in this situation. I am not that familiar with them but felt I would give this a shot using them. Without them, using your approach, you will have to check somehow all the case possibilities. That’s where regular expressions are your friend. Below is the code that creates a regular expression from the text in the text box. Then I use that expression to get the Matches in the text in the RichTexBox to highlight. Hope this helps.
private void button1_Click(object sender, EventArgs e) {
richTextBox1.SelectAll();
richTextBox1.SelectionBackColor = Color.White;
if (textBox1.Text.Length < 1)
return;
string pattern = #"\b" + textBox1.Text.Trim() + #"\b";
Regex findString = new Regex(pattern, RegexOptions.IgnoreCase);
foreach (Match m in findString.Matches(richTextBox1.Text)) {
richTextBox1.Select(m.Index, m.Length);
richTextBox1.SelectionBackColor = Color.Yellow;
}
}
You could do your search by adding Text.ToUpper() method.
Add .ToUpper() method in your richTextBox1.Text and search text both.
As mentioned use the ToUpper() or ToLower() method for all texts that you operate with. But I also wonder if you shouldn't add the event to search while typing instead of waiting for full string. That would be more intuitive and easier to troubleshoot at all.

TextBox text "Replace" function does not work well

I have already looked at similar questions here but it did not help.
I am using windows forms. I have button1 and textbox1.
I am trying to replace (or delete) the selected text in textBox1 and enter new letter (letter A) in place of it.
The code works well with random mixed numbers and letters
for example:
385F1 select 8 and then result = 3A5F1 (8 replaced by A)
H74S31B select 4S and then the result is = H7A31B
KQ5689 select Q5689 and then the result is KA
So it works well, but when I select a number or a letter from a string which consists of same numbers or letters then it does not work, for example:
666777222333 select any 7 then the result = 666AAA222333 (not
working)
9992244GG select any 9 then the result = AAA2244GG (not working)
QQQHHHUUU select any Q then the result = AAAHHHUUU (not working)
QQQHHHUUU select any QH then the result = QQAHHUUU(it works when
different letters selected)
4433366 select 333 then the result = 44A66 (it works when all same
numbers is selected)
Hope I explained it well. I don't know what causes this behavior. please help. Thank you
public partial class Form1 : Form
{
int TxTindex;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ActiveControl = textBox1;
textBox1.Focus();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Focus();
if (textBox1.SelectedText.Length > 0) // to check if any text selected
{
TxTindex = textBox1.SelectionStart; // save the caret position
textBox1.Text = textBox1.Text.Replace(textBox1.Text.Substring(textBox1.SelectionStart, textBox1.SelectionLength),"A");
textBox1.SelectionStart = TxTindex + 1; // place the caret after the inserted string
}
else
{
return;
}
}
}
Your problem is here :
textBox1.Text = textBox1.Text.Replace(textBox1.Text.Substring(textBox1.SelectionStart, textBox1.SelectionLength),"A");
The Substring function returns string. In your example (666777222333 select any 7 then the result = 666AAA222333 (not working)), it returns "7". But Text.Replace will replace all occurrences of 7. That is not what you want. What you can do is, instead of using string.Replace function, use string.Remove and string.Insert
textBox1.Text = textBox1.Text.Remove(textBox1.SelectionStart, textBox1.SelectionLength).Insert(textBox1.SelectionStart, "A");
But this might not be very efficient for large strings. A StringBuilder would be better.
The problem is caused by the usage of string.Replace function.
What you are trying to accomplish can be done simply by
if (textBox1.SelectionLength > 0)
textBox1.SelectedText = "A";
There is no need to save/set selection start.

How to store a line in a text file into an array?

I have a problem, which i cannot face with. I want the program (as seen below) to store all the line of the question located in "temp_q.txt" file. for example this is a question:
C1: Who is John Smith?
And save the words of the question on an array, and then if it finds the answer in the "book" whitch I have named "core.txt" It will show the answer into textbox.2
Here is the part of the code:
private void button2_Click(object sender, EventArgs e)
{
if (File.Exists(#"C:\\Users\TEI\Desktop\temp_q.txt"))
{
//OK, pff..Now search for the question to answer!
System.IO.StreamReader keytxt = new System.IO.StreamReader(#"C:\\Users\TEI\Desktop\temp_q.txt");
String line;
while ((line = keytxt.ReadLine()) != null)
{
if (line.Contains(textBox1.Text)) //If the question has been found...
{
String ctrl1 = String.Empty;
ctrl1 = ("Line Found!Beginning Voice Transfer..");
richTextBox2.Text = ctrl1;
//Here i want to save the question word-by-word in an array.
//Begin searching for the right answer in the core
}
}
Every little help is aprreciated!
Thank you in advance!
For saving the question word by word into an array, you could just simple declare an array in your code and put the question into a string variable and ultimately use the Split(' ') function to split it into individual words. Something like this :
string question = "Who is John Smith?";
string[] words = new string[100];
words = question.Split(' ');
You can define the array-size as per your requirement here. This will break up the entire question by the whitespaces that are present in between the words.
UPDATE : Finding the word in Core.txt part :
Now when you want to search for some particular word in that text file, you can loop through the array that we have just made, one element at a time, searching for a match in your line object. Something like this :
for (int i = 0; i < words.Length; i++)
{
if(line.Contains(words[i].ToString()))
{
//put your logic here.
}
}
Hope this helps.

Select Text in a multiline textbox, move it to another multiline textbox on a button click in C#

I have a problem that I haven't come across yet that I hope some of you may help me with. I am trying to select a single line, either the fist, second, or last line in a multiline textbox and move it to another multiline textbox with a button click in C#. I am unsure how to select just a single line at a time, then add it to the other multiline textbox. If anyone has some insight, that would be great! Thank you!
Brent
Well, assuming that you are defining a "line" as a complete string of characters separated by other similar strings with a newline character, and not simply as the string of characters visible in a single horizontal plane in a text field with word wrap property set to true.....
public void Button1_Click(object sender, ClickEventArgs e)
{
//get the values of both boxes
string value1 = TextBox1.Text.Trim();
string value2 = TextBox2.Text.Trim();
//split the value from the source box on its new line characters
string[] parts = value1.split(Environment.NewLine);
string last_line = parts[parts.length -1];
//add the last row from the source box to the destination box
value2 += (Environment.NewLine + last_line);
//set the last_line in the source to an empty string
parts[parts.Length -1] = String.Empty;
//put the new values back in their text boxes
TextBox1.Text = String.Join(Environment.NewLine, parts).Trim();
TextBox2.Text = value2;
}
If you are dealing with visible line and word wrapped that is a whole 'nother ball game and the answer is dependant on if you are talking ASP, or Win App. Also, this was written off the cuff, so you may need to tweak a character or two to get it to compile. No Warranties, LOL.
Something like this will work:
public void Button1_Click(object sender, ClickEventArgs e)
{
string text = TextBox1.Text;
// spliting text on the basis on newline.
string[] myArray = text.Split(new char[] { '\n' });
foreach (string s in myArray)
{
//Line by line copy
TextBox2.Text += s;
}
}
Try something like this:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Lines.Length > 0)
{
textBox2.Text += textBox1.Lines[textBox1.GetLineFromCharIndex(textBox1.SelectionStart)];
}
}
What it is doing is using the GetLineFromCharIndex with the SelectionStart caret location as the char Index to pull the Line out of the TextBox.Lines array

Simple problem with replacing string value C#

i'm in a bit of a bind with a problem that's supposed to mediocre, but seemingly i can't implement the solution.
I have buttons, with a single char on each of them, 26 to be exact (english alphabet),
When i click any of them, the loop iterates through the string for the text value on the buttons and replaces it with quotation marks.
The code works, and it prints out the newAlphabet without the clicked character. But when i click another button, it returns the newAlphabet albeit with the previously removed character and removes the new clicked character.
The code is as follows
static string alphabet = "abcdefghijklmnopqrstuvwxyz";
static string newAlphabet = string.Empty;
Button tempBtn = (Button)sender;
for (int i = 0; i < alphabet.Length; i++)
{
if (alphabet[i].ToString().Contains(tempBtn.Text))
{
newAlphabet = alphabet.Replace(tempBtn.Text, "");
MessageBox.Show(newAlphabet);
}
}
Sorry for grammar or spelling errors, english is not my first language.
Regards, HC
This line
newAlphabet = alphabet.Replace(tempBtn.Text, "");
means you're always getting back to "abcdefghijklmnopqrstuvwxyz" and replacing that.
If you want to keep replacing letters, you need to replace on newAlphabet.
A simpler solution would be:
static string alphabet = "abcdefghijklmnopqrstuvwxyz";
private void button1_Click(object sender, EventArgs e)
{
var tempBtn = (Button)sender;
alphabet = alphabet.Replace(tempBtn.Text, "");
MessageBox.Show(alphabet);
}
Note 1:
If the code you posted is in your button click event method then it would not compile. In C# you cannot declare variables static inside methods.
Note 2:
Strings are immutable so alphabet.Replace() returns a new string without affecting the original.
If the goal is to remove the clicked letter from the list:
static string newAlphabet = "abcdefghijklmnopqrstuvwxyz";
Button tempBtn = (Button)sender;
newAlphabet = newAlphabet.Replace(tempBtn.Text, "");
MessageBox.Show(newAlphabet);
Please note that strings are immutable in C#. "newAlphabet" is being continuously replaced by a modified "alphabet". It will never stick.

Categories