Getting certain characters in a textbox - c#

Let's say I wanted to create a simple calculator, and I have it set up so whenever you press one of the operation buttons (+,-,*,/), it sets whatever you have in the textbox as the first number and then add the operation to the textbox. Now if I wanted the second number to be set to whatever is after the operation (+,-,*, or /) when I press the solve button, how would I go about doing that?

You can use the string Split method to get your factors like this:
string calculation = "5+1";
string[] factors = calculation.Split('+');
//factors[0] == 5
//factors[1] == 1
To handle string splitting on multiple operands use:
string calculation = "4+8-2";
string[] factors = calculation.Split(new char[] {'+' , '-' });
//factors[0] == 4
//factors[1] == 8
//factors[2] == 2

Related

Check if 2 textboxes have the same data type

I am trying to make a Kinematics Calculator on C#, you input 3 numerical values, a letter and a question mark (each in different text boxes). The letters change depend on the value you are inputting. For example, you would input "A" for acceleration but "T" for time. Unfortunately, the problem is I need a function that finds if 2 letters are present in 2 different text boxes and display a message box saying you cannot do that, etc
For example,
If I had a textbox that had a user input of "A" and another textbox that had a user input of "T", then I need a message box that outputs "Only 1 letter allowed, please try again".
Is there a way to do this?
You could do a "tryParse" on each text field. If it fails you know there is a character present. You then count the amount of "fails". There are many different ways to detect how many alpha characters there are. You may need to strip the "?" field with .Replace("?","") too.
int parsedValue = 0;
int lettersPresent = 0;
if (!int.TryParse(textBox1.Text, out parsedValue)) lettersPresent++;
if(!int.TryParse(textBox2.Text, out parsedValue)) lettersPresent++;
if (lettersPresent > 1) MessageBox.Show("Only 1 letter allowed, please try again");
It may be easier to just combine the textbox values and check with contains as well:
string combined = textBox1.Text + textBox2.Text;
int letterCount = 0;
if (combined.Contains("T")) letterCount++;
if (combined.Contains("S")) letterCount++;
if (letterCount > 1) MessageBox.Show("Too many..");
I am assuming you are parsing the letters out at some point so it probably should just be included inside that method.
You can use Char.IsLetter() method alongside the LINQ Any()to achieve that. Char.IsLetter() method will return true if the provided char is an uppercase or lowercase letter. Note that if any of the chars of the string is a letter, the expression return will return true, if you need to check if all the characters of the string are a letter, use .All() instead of .Any()
string textbox1Value = "V";
string textbox2Value = "T";
bool hasTwoLetters = textbox1Value.Any(x => char.IsLetter(x)) && textbox2Value.Any(x => char.IsLetter(x));
if(hasTwoLetters)
{
// Display alert
}

How to pick out specific parts of a text box?

I am trying to pick out specific letters/numbers from a text box, because each means something. After that I am trying to display in a label what it means.
So if I have a number AB-123456, I need to first pick out AB something like:
If (textBox.Text.Substring(0,2) == "AB") {
//Display to a label
}
First off, this doesn't work and I also tried substring(0,1) but also was receiving errors when I used my clear button to clear the text box.
After that I still need to pull the rest of the numbers. The next one I need to pull and define is 123, then 4 by itself, 5 by itself, and six by itself.
How do I go about pulling each of these individually if substring isnt working?
Try this:
if (textBox.Text.StartsWith("AB"))
{
//Display to a label
}
Use this if you don't want to have to check the Length of the text first. Also, you can include a StringComparison argument if you want to ignore case.
string input = textBox.Text;
// check the length before substring
If (input.Length >= 2 && input.Substring(0,2) == "AB") {
//Display to a label
}
or use regex:
string txt="AB-1234562323";
string re="AB-(\\d+)"; // Integer Number 1
Regex r = new Regex(re,RegexOptions.IgnoreCase|RegexOptions.Singleline);
Match m = r.Match(txt);
if (m.Success)// match found
{
// get the number
String number=m.Groups[1].ToString();
}

how to get text after a certain comma on C#?

Ok guys so I've got this issue that is driving me nuts, lets say that I've got a string like this "aaa,bbb,ccc,ddd,eee,fff,ggg" (with out the double quotes) and all that I want to get is a sub-string from it, something like "ddd,eee,fff,ggg".
I also have to say that there's a lot of information and not all the strings look the same so i kind off need something generic.
thank you!
One way using split with a limit;
string str = "aaa,bbb,ccc,ddd,eee,fff,ggg";
int skip = 3;
string result = str.Split(new[] { ',' }, skip + 1)[skip];
// = "ddd,eee,fff,ggg"
I would use stringToSplit.Split(',')
Update:
var startComma = 3;
var value = string.Join(",", stringToSplit.Split(',').Where((token, index) => index > startComma));
Not really sure if all things between the commas are 3 length. If they are I would use choice 2. If they are all different, choice 1. A third choice would be choice 2 but implement .IndexOf(",") several times.
Two choices:
string yourString="aaa,bbb,ccc,ddd,eee,fff,ggg";
string[] partsOfString=yourString.Split(','); //Gives you an array were partsOfString[0] is "aaa" and partsOfString[1] is "bbb"
string trimmed=partsOfString[3]+","+partsOfString[4]+","+partsOfString[5]+","+partsOfSting[6];
OR
//Prints "ddd,eee,fff,ggg"
string trimmed=yourString.Substring(12,14) //Gets the 12th character of your string and goes 14 more characters.

Clip string inside of Array

Lets say I have a String Array full of items such as:
string[] letters = new string[4] {"A1","B1","C1","D1"};
Later, I want to set the contents of a textbox to the first value in the array:
Letter.Content = letters[0];
Is there a way to 'clip' the number out of the String in the Array? For example, in my above code, currently the Letter textbox would be set to 'A1'. What I want however is to set it to just 'A'.
Depends on if the strings's length is always two and the digit is at the second position. Then it's simple:
Letter.Content = letters[0][0];
If you don't know the length but you want to take all letters from the left until there is a non-letter you could use string.Concat + LINQ:
Letter.Content = string.Concat(letters[0].TakeWhile(Char.IsLetter));
or you could do it the old fashion way using SubString Method
Letter.Content = letters[0].Substring(0,1);

How to Generate Sub String values From Value inserted in multiple textboxes

i have 2 tables in my database.1st is material_details and 2nd is category
in material_details i have 6 columns (Make,Series,capacitance,tolerance,material outing)
in 2nd i have(category id,category_Name)
i want to take values from users in text boxes and from that values want to generate a sub string.how can i do this? code in c sharp
this will make u understand better.......
"i am working on a demo website.on my webpage i have 5 labels and 5 text boxes. 1.category 2.make 3.series 4.capacity and the last text box is Sub string.Now i want that when ever the user fill the 1 to 4 text boxes.a sub string should be generated by the values of these text boxes..for example..if user enter the category as "school" make as "samsung" series as "1234" the sub string that will be generates is like "SCH-SAM-123"..the first three words from all field.""
//these codes will help you retrieve the values of each Text box to strings
TextBox objTextBox1 = (TextBox)input1;
string theText1 = objTextBox.Text;
Similarly generate 4 strings for each text box.
theText1
theText2
theText3
theText4
//This will extract first three characters from a string
string sub1 = theText1.Substring(0, 3);
Similarly extract characters from all the strings created above.
If you want the characters to be in upper case use "string.ToUpper()" method
Once all the strings are extracted, concatenate all strings
string results = sub1 + "-" + sub2 + "-" + sub3 "-" + sub4;
//Check the result
Console.WriteLine(results);
I hope this guide will help you to get your intended results.
Thanks

Categories

Resources