This code i used to text change as i need.
private void textBox1_TextChanged(object sender, EventArgs e)
{
string A = textBox1.Text.Trim();
A = A.Replace("A", "C");
A = A.Replace("F", "H");
A = A.Replace("C", "W");
A = A.Replace("B", "G");
textBox2.Text = (A);
}
Now i need to stop text changing after,
if i type '|' symbol in tetxbox1, Again i need to
start text changing if i type '|' symbol again,such as happened thing in this image.
So how can i prevent text changing between these two symbols only ||
You're replace code won't work how you have it, as it will just keep changing the characters for the same string(you change A to C, and later down you change C to W, so your final first character would be W and not C like you want).
Below is an overly complicated method(i also added a method that runs through each character of the string doing the replace) but it should work, and you can change as needed. Good luck
private void textBox1_TextChanged(object sender, EventArgs e)
{
string A = textBox1.Text.Trim();
string[] Aarry = A.Split('|');
string cleanedString = "";
for (int i = 0; i < Aarry.Length; i++)
{
if (i % 2 == 0)
cleanedString += FixText(Aarry[i]) + " ";
else
cleanedString += Aarry[i] + " ";
}
textBox2.Text = cleanedString ;
The method below will go through each character doing the replace
public string FixText(string A)
{
string newText = "";
for (int i = 0; i < A.Length; i++)
{
switch (A.Substring(i, 1))
{
case "A":
newText += A.Substring(i, 1).Replace("A", "C");
break;
case "F":
newText += A.Substring(i, 1).Replace("F", "H");
break;
case "C":
newText += A.Substring(i, 1).Replace("C", "W");
break;
case "B":
newText += A.Substring(i, 1).Replace("B", "G");
break;
default:
break;
}
}
return newText;
}
To handle the >500 lines of replacement type you have, you could setup a dictionary using method below:
public Dictionary<string, string> ReturnReplacementDictionary()
{
Dictionary<string, string> dictLibrary = new Dictionary<string,string)()
{
{"A","C"},
{"F","H"},
{"C","W"},
{"B","G"}
};
return dictLibrary;
}
In the above you would just continue adding in all your other replacement values.
Then you would call use that method below instead of the switch case(If you don't add a character/replacement to the dictionary method you can see it will just set the replacement character to blank):
public string FixTextUsingDictionary(string A)
{
Dictionary<string, string> replaceDict = ReturnReplacementDictionary();
string newText = "";
for (int i = 0; i < A.Length; i++)
{
string replacementLetter="";
if (replaceDict.TryGetValue(A.Substring(i, 1), out replacementLetter))
{
newText += replacementLetter;
}
// Added so that if the char is not in the dictionary the output will just have the original char
else { newText += A.Substring(i, 1); }
}
return newText;
}
Good luck
If the text is entered manually not pasted from clipboard, my solution will be:
int counter = 0;
private string replaceSpecial(string A)
{
if (A.Equals("A")) return "C";
else if (A.Equals("F")) return "H";
else if (A.Equals("C")) return "W";
else if (A.Equals("B")) return "G";
else if (A.Equals("|")) return "";
else return A;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar.Equals('|'))
{
counter++;
}
if (counter == 0 || counter % 2 == 0)
textBox2.Text += replaceSpecial(e.KeyChar.ToString());
else
textBox2.Text += e.KeyChar.ToString().Replace("|", "");
}
considering that the only entered character is "|".
good luck
void StringReplace(string initialString)
{
bool insideSpecialCharacter = false;
string[] Pattern = { "A-C", "C-W", "F-H", "B-G" };
string specialCharacter = "|";
char[] characters = initialString.ToCharArray();
char?[] Newcharacters = new char?[characters.Length];
for (int i = 0; i < characters.Length; i++)
{
if (!characters[i].ToString().Equals(specialCharacter))
{
if (insideSpecialCharacter)
{
Newcharacters[i] = characters[i];
}
else
{
CheckPattern(Pattern, characters, Newcharacters, i);
}
}
else
{
insideSpecialCharacter = (insideSpecialCharacter) ? false : true;
}
}
txtSecond.Text = string.Concat(Newcharacters).Trim();
}
//-------Checks the Pattern Array and Replaces the Characters-----------
private static void CheckPattern(string[] Pattern, char[] characters, char?[] Newcharacters, int i)
{
for (int j = 0; j < Pattern.Length; j++)
{
string[] replaceValue = Pattern[j].Split('-');
if (characters[i].ToString() == replaceValue[0])
{
Newcharacters[i] = Convert.ToChar(characters[i].ToString().Replace(characters[i].ToString(), replaceValue[1]));
break;
}
else
{
Newcharacters[i] = characters[i];
}
}
}
Related
Can somebody tell me what I am doing wrong please? can't seem to get the expected output, i.e. ignore whitespace and only upper/lowercase a-z characters regardless of the number of whitespace characters
my code:
var sentence = "dancing sentence";
var charSentence = sentence.ToCharArray();
var rs = "";
for (var i = 0; i < charSentence.Length; i++)
{
if (charSentence[i] != ' ')
{
if (i % 2 == 0 && charSentence[i] != ' ')
{
rs += charSentence[i].ToString().ToUpper();
}
else if (i % 2 == 1 && charSentence[i] != ' ')
{
rs += sentence[i].ToString().ToLower();
}
}
else
{
rs += " ";
}
}
Console.WriteLine(rs);
Expected output: DaNcInG sEnTeNcE
Actual output: DaNcInG SeNtEnCe
I use flag instead of i because (as you mentioned) white space made this algorithm work wrong:
var sentence = "dancing sentence";
var charSentence = sentence.ToCharArray();
var rs = "";
var flag = true;
for (var i = 0; i < charSentence.Length; i++)
{
if (charSentence[i] != ' ')
{
if (flag)
{
rs += charSentence[i].ToString().ToUpper();
}
else
{
rs += sentence[i].ToString().ToLower();
}
flag = !flag;
}
else
{
rs += " ";
}
}
Console.WriteLine(rs);
Try a simple Finite State Automata with just two states (upper == true/false); another suggestion is to use StringBuilder:
private static string ToDancing(string value) {
if (string.IsNullOrEmpty(value))
return value;
bool upper = false;
StringBuilder sb = new StringBuilder(value.Length);
foreach (var c in value)
if (char.IsLetter(c))
sb.Append((upper = !upper) ? char.ToUpper(c) : char.ToLower(c));
else
sb.Append(c);
return sb.ToString();
}
Test
var sentence = "dancing sentence";
Console.Write(ToDancing(sentence));
Outcome
DaNcInG sEnTeNcE
I think you should declare one more variable called isUpper. Now you have two variables, i indicates the index of the character that you are iterating next and isUpper indicates whether a letter should be uppercase.
You increment i as usual, but set isUpper to true at first:
// before the loop
boolean isUpper = true;
Then, rather than checking whether i is divisible by 2, check isUpper:
if (isUpper)
{
rs += charSentence[i].ToString().ToUpper();
}
else
{
rs += sentence[i].ToString().ToLower();
}
Immediately after the above if statement, "flip" isUpper:
isUpper = !isUpper;
Linq version
var sentence = "dancing sentence";
int i = 0;
string result = string.Concat(sentence.Select(x => { i += x == ' ' ? 0 : 1; return i % 2 != 0 ? char.ToUpper(x) : char.ToLower(x); }));
Sidenote:
please replace charSentence[i].ToString().ToUpper() with char.ToUpper(charSentence[i])
Thanks #Dmitry Bychenko. Best Approach. But i thought as per the OP's (might be a fresher...) mindset, what could be the solution. Here i have the code as another solution.
Lengthy code. I myself don't like but still representing
class Program
{
static void Main(string[] args)
{
var sentence = "dancing sentence large also";
string newString = string.Empty;
StringBuilder newStringdata = new StringBuilder();
string[] arr = sentence.Split(' ');
for (int i=0; i< arr.Length;i++)
{
if (i==0)
{
newString = ReturnEvenModifiedString(arr[i]);
newStringdata.Append(newString);
}
else
{
if(char.IsUpper(newString[newString.Length - 1]))
{
newString = ReturnOddModifiedString(arr[i]);
newStringdata.Append(" ");
newStringdata.Append(newString);
}
else
{
newString = ReturnEvenModifiedString(arr[i]);
newStringdata.Append(" ");
newStringdata.Append(newString);
}
}
}
Console.WriteLine(newStringdata.ToString());
Console.Read();
}
//For Even Test
private static string ReturnEvenModifiedString(string initialString)
{
string newString = string.Empty;
var temparr = initialString.ToCharArray();
for (var i = 0; i < temparr.Length; i++)
{
if (temparr[i] != ' ')
{
if (i % 2 == 0 && temparr[i] != ' ')
{
newString += temparr[i].ToString().ToUpper();
}
else
{
newString += temparr[i].ToString().ToLower();
}
}
}
return newString;
}
//For Odd Test
private static string ReturnOddModifiedString(string initialString)
{
string newString = string.Empty;
var temparr = initialString.ToCharArray();
for (var i = 0; i < temparr.Length; i++)
{
if (temparr[i] != ' ')
{
if (i % 2 != 0 && temparr[i] != ' ')
{
newString += temparr[i].ToString().ToUpper();
}
else
{
newString += temparr[i].ToString().ToLower();
}
}
}
return newString;
}
}
OUTPUT
I have a program where i need to count how many females and Males are in the file that has been read into the richtextbox, but I'm not sure how to do that , in the file has the name, gender,specific job . I have to count between 15 different people
for example : " Donna,Female,Human Resources.",
This is what I have so far:
private void Form1_Load(object sender, EventArgs e)
{
StreamReader sr;
richTextBox1.Clear();
sr = new StreamReader("MOCK_DATA.txt");
string data;
while (!sr.EndOfStream)
{
data = sr.ReadLine();
richTextBox1.AppendText(data + "\n");
}
}
private void button1_Click(object sender, EventArgs e)
{
string[] data = richTextBox1.Text.Split(',');
for (int n = 0; n < data.Length; n++)
{
if (data[n] == richTextBox1.Text)
n++;
To get the plain text from a RichTextBox (stolen from this article):
string StringFromRichTextBox(RichTextBox rtb)
{
TextRange textRange = new TextRange(
// TextPointer to the start of content in the RichTextBox.
rtb.Document.ContentStart,
// TextPointer to the end of content in the RichTextBox.
rtb.Document.ContentEnd
);
// The Text property on a TextRange object returns a string
// representing the plain text content of the TextRange.
return textRange.Text;
}
Basic word counting routine:
int CountWord(string textToSearch, string word)
{
int count = 0;
int i = textToSearch.IndexOf(word);
while (i != -1)
{
count++;
i = textToSearch.IndexOf(word, i+1);
}
return count;
}
Putting it together:
var plainText = StringFromRichTextBox(richTextBox1);
var countOfMale = CountWord(plainText, "Male");
var countOfFemale = CountWord(plainText, "Female");
private void toolStripButton81_Click(object sender, EventArgs e)
{
string findterm = string.Empty;
findterm = toolStripTextBox2.Text;
// the search term - specific word
int loopCount = 0;
// count the number of instance
int findPos = 0;
// depending on checkbox settings
// whole word search or match case etc
try
{
while (findPos < GetRichTextBox().Text.Length)
{
if (wholeWordToolStripMenuItem.CheckState == CheckState.Checked & matchCaseToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.WholeWord | RichTextBoxFinds.MatchCase);
}
else if (wholeWordToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.WholeWord);
}
else if (matchCaseToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.MatchCase);
}
else
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.None);
}
GetRichTextBox().Select(findPos, toolStripTextBox2.Text.Length);
findPos += toolStripTextBox2.Text.Length + 1;
loopCount = loopCount + 1;
}
}
catch
{
findPos = 0;
}
// at the end bring the cursor at the beginning of the document
GetRichTextBox().SelectionStart = 0;
GetRichTextBox().SelectionLength = 0;
GetRichTextBox().ScrollToCaret();
// Show the output in statusbar
toolStripStatusLabel2.Text = "Instances: " + loopCount.ToString();
}
my code don't change anything in the file.
here's my code.
i try to find the name of the user by idx of line and than to change the needed change but the txt file stay as he was ,the method "read names" reading the names of all the people by split and its works.
read file method read all the lines to array of lines.
update arr is method that get the new lines array and replace it with the first one.
findidxbyusename find the idx of the line of the selected username
public string[] readNames()
{
string[] lines = System.IO.File.ReadAllLines(#"c:/aab/passwords.txt");
string tmpName;
string[] arr = new string[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
tmpName = lines[i].Split(new[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries)[0];
arr[i] = tmpName;
}
return arr;
}
public string[] readFile()
{
string[] lines = System.IO.File.ReadAllLines(#"c:/aab/passwords.txt");
return lines;
}
public void updateArr(string[] arr)
{
string content = "";
for (int i = 0; i < arr.Length; i++)
{
content += arr[i] + "\r\n";
}
File.WriteAllText("c:/aab/passwords.txt", content);
}
public int FindidxOfUser(string username)
{
string[] arr = readFile();
int idx = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].Split(new[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries)[0].Equals(username))
{
idx = i;
}
}
return idx;
}
private void usersEdit_Load(object sender, EventArgs e)
{
string[] arr = readNames();
for (int i = 0; i < arr.Length; i++)
{
comboBox2.Items.Add(arr[i]);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text.Equals("User name"))
{
label2.Text = "New User Name :";
textBox1.Visible = true;
}
else
{
label2.Text = "New Password :";
textBox1.Visible = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
string username = comboBox2.Text;
int idx = FindidxOfUser(username);
string[] arr = readFile();
if (comboBox1.Text.Equals("User name"))
{
arr[idx].Split(',')[0] = textBox1.Text;
updateArr(arr);
MessageBox.Show(comboBox1.Text + " Changed Succesfully!", "Succes!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Hide();
}
else if (comboBox2.Text.Equals("Password"))
{
arr[idx].Split(',')[1] = textBox1.Text;
updateArr(arr);
MessageBox.Show(comboBox1.Text + " Changed Succesfully!", "Succes!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Hide();
}
else
{
MessageBox.Show("Shlomi you are a dom ass", "Succes!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Hide();
}
}
You aren't actually assigning the value to the arr[idx] string with the following code:
arr[idx].Split(',')[0] = textBox1.Text
It is actually splitting the string which creates a string array, and then setting the first value to the textbox text. You aren't actually assigning a value to the arr[idx] string but instead the in-memory array of strings. It's a subtle difference but the reason your code isn't working.
You can change the line to the following to make it "stick":
string[] arrElements = arr[idx].Split(',');
arrElements[0] = textBox1.Text;
arr[idx] = String.Join(arrElements, ",");
updateArr(arr);
You would then need to do the same where you are setting the password. The key is that you are assigning the value to the actual arr[idx] this way rather than the temporary string array from the split.
Hello Everyone,
As shown in the above image I want to add the decimal numbers column wise from a text file to datagrid control.
Following is my code snippet
List<string> str = new List<string>();
String st = "";
int k = 0;
string[] s ;
//Path to write contents to text file
string filename = #"E:\Vivek\contentcopy\clientlist.txt";
Form.CheckForIllegalCrossThreadCalls = false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.FileName = "";
ofd.ShowDialog();
st = ofd.FileName;
if (string.IsNullOrEmpty(ofd.FileName))
return;
string Name = "", No1 = "",No2="";
string[] lines = File.ReadAllLines(st).Where(sw => !string.IsNullOrWhiteSpace(sw)).ToArray();
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("VENTURA SECURITIES LIMITED (NSE F&O)")) continue;
if (lines[i].Contains("ALL EXCHANGES DERIVATIVES CLIENTWISE STATEMENT AS ON 16-05-2012")) continue;
if (lines[i].Contains("-------------------------------------------------------")) continue;
s = lines[i].Split(' ');
if (s[0] == "PARTY" || s[0] == "") continue;
int z;
Name = "";
for (z = 1; z < s.Length; z++)
{
if (s[z] == "") continue;
if (s[z].Contains('.'))
{
No1+=s[z]+" ";
No2 = No1 + " ";
}
else
{
Name += s[z];
str.Add(s[0]+" "+Name);
}
}
dataGridView1.Rows.Add();
dataGridView1.Rows[k].Cells[0].Value = s[0];
dataGridView1.Rows[k].Cells[1].Value = Name;
dataGridView1.Rows[k].Cells[2].Value = No1;
dataGridView1.Rows[k].Cells[3].Value = No2;
k++;
}
File.WriteAllLines(filename, str);
dataGridView1.ReadOnly = true;
}
The line No1=s[z] directly takes the last column values ie 46,123.19 and so on.I want to fetch each column from the text file and store it in a string variable and then assign it to the datagrid view
I hope my doubt is clear.If not please let me know
Here is the simplest Solution:
Add a DataGrid View to Form and add a Button:
private void button1_Click(object sender, EventArgs e)
{
ReadAndFileter();
}
private void ReadAndFileter()
{
try
{
using(System.IO.StreamReader reader = new System.IO.StreamReader("file.txt"))
{
string line;
string []array;
int rowcount= 0;
decimal number;
string[] separators = { "\t", " " };
int columnCount = 0;
while ((line = reader.ReadLine()) != null)
{
array = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);
dataGridView1.Rows.Add();
foreach (string str in array)
{
if (Decimal.TryParse(str,out number))
{
dataGridView1.Rows[rowcount].Cells[columnCount++].Value = number;
}
}
rowcount++;
columnCount = 0;
}
}
}
catch (Exception ex)
{
}
}
The File Contents are:
Abc 20.122 69.33 0.00 693.25 0.00
def 36.20 96.20 1.15 69.56 8.96
And the final output:
Lets say, you have for lines in your test file, then u need to do following things:
Use StreamReader.ReadLine(), to read one line at time.
Spilt the line using split(' ') and store it in a array
Remove all the empty ones from the array
Now at index 2,3,4,5,6 of the resulting array will have the string equivalent of the decimal numbers.
Repeat this for each StreamReader.ReadLine()
Hope this will help.
Your problem is that you are overwriting No1 every time you read a string, which explains why you only get the last value. What you could do is either;
Append the string:
No1 += s[z] + " ";
Which will put all the values behind eachother, seperated by a whitespace.
Or, you could make a List<String> and add each value to the list, meaning you have them stored seperated:
List<String> values = new List<String>();
foreach(...)
{
if (s[z] == "") continue;
if (s[z].Contains('.'))
{
values.Add(s[z])
}
else
{
Name += s[z];
str.Add(s[0] + " " + Name);
}
}
You can thereafter loop through the list and add each value to a row. Considering your code piece;
int i = 2;
foreach(string value in values)
{
dataGridView1.Rows[k].Cells[i].Value = value;
i++;
}
This should work.
Hope this helps.
Here is edited code: but for future I must suggest to give a try at least..
private void ReadAndFileter1()
{
try
{
using (System.IO.StreamReader reader = new System.IO.StreamReader("file.txt"))
{
string line;
string[] array;
int rowcount = 0;
decimal number;
string[] separators = { "\t", " " };
int columnCount = 1;
string[] lines = File.ReadAllLines("file.txt");
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("VENTURA SECURITIES LIMITED (NSE F&O)")) continue;
if (lines[i].Contains("ALL EXCHANGES DERIVATIVES CLIENTWISE STATEMENT AS ON 16-05-2012")) continue;
if (lines[i].Contains("-------------------------------------------------------")) continue;
array = lines[i].Split(separators, StringSplitOptions.RemoveEmptyEntries);
if (array[0] == "PARTY" || array[0] == "") continue;
dataGridView1.Rows.Add();
foreach (string str in array)
{
if (Decimal.TryParse(str, out number))
{
dataGridView1.Rows[rowcount].Cells[columnCount++].Value = number;
}
}
dataGridView1.Rows[rowcount].Cells[0].Value = array[0];
rowcount++;
columnCount = 1;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Here it is:
static void Main(string[] args)
{
Decimal result;
string[] splitchar = new string[]{" "};
using(StreamReader reader = new StreamReader(#"C:\Users\Dell\Desktop\input.txt"))
{
while(!reader.EndOfStream)
{
string[] splittedArray = reader.ReadLine().Split(splitchar, StringSplitOptions.RemoveEmptyEntries).Where(x => Decimal.TryParse(x, out result)).ToArray();
// put your code here to get insert the values in datagrid
}
}
}
I want to be able to use a RegEx to parse out ranges like a Windows Print dialog (such as 1-50,100-110,111,112). The following is my current code and I am not clear on how to parse for the additional commas and numbers. I can parse out the hyphen, but not sure how to do it for additional commas or hyphens
private void tboxRowNum_Leave(object sender, EventArgs e)
{
Regex.Replace(tboxRowNum.Text, #"(?<first>\d+)-(?<last>\d+)",
new MatchEvaluator(this.parseSpaceDefinition));
}
private string parseSpaceDefinition(Match m)
{
int first = int.Parse(m.Groups["first"].Value);
int last = int.Parse(m.Groups["last"].Value);
StringBuilder sb = new StringBuilder(first.ToString());
for (int i = first + 1; i <= last; i++)
{
if (spaceItems == 0)
{
if (isNumeric(sb.ToString(), System.Globalization.NumberStyles.Integer))
{
startingSpace = Convert.ToInt32(sb.ToString());
}
}
sb.Append("," + i.ToString().Replace(" ", ""));
spaceItems++;
endingSpace = i;
}
tboxRowDesc.Text = sb.ToString();
return sb.ToString();
}
Edit 1: The modified code gets me what I want:
private void tboxRowNum_Leave(object sender, EventArgs e)
{
string[] parts = tboxRowNum.Text.Split(',');
for (int i = 0; i < parts.Length; i++)
{
if (parts[i].IndexOf('-') >= 0)
{
Regex.Replace(parts[i], #"(?<first>\d+)-(?<last>\d+)",
new MatchEvaluator(this.parseSpaceDefinition));
}
else
{
int number;
if(!(int.TryParse(parts[i], out number)))
{
MessageBox.Show("Incomplete/Invalid formula", "Invalid Space Definition");
tboxRowDesc.Text = "";
}
else
{
tboxRowDesc.Text += "," + number;
spaceItems++;
}
}
}
}
string[] ranges = inputString.split(',');
foreach (string rangeCandidate in ranges) {
// See if matches regex
}
Split it first on comma, and for each part check if it matches your regexp. If it does, do what you are already doing, otherwise just use int.Parse (or int.TryParse for robustness).