I have an string which is always 12 digits long
Its starts with 'PSS1'
'PSS100000300'
So I need to extract '300'
I can't just grab the last 3 digits as the number can increase to say
'PSS100010300'
And would need the value extracted to be '10300'
If I understood correctly, you want to skip first 4 characters and then zeross till the first non-zero characters. Try this one:
s = new string(s.Substring(4).SkipWhile(x => x == '0').ToArray());
Or, as #Blorgbeard suggested,
s = int.Parse(s.Substring(4)).ToString();
There is a slight difference between the methods. If you pass "PSS100000000", the first one returns an empty string, the second one returns "0". Not sure which result is expected.
Try this :
s = Convert.ToInt32(s.Replace("PSS1", string.Empty)).ToString()
The only problem with using int.Parse is that if you happen to ever come across this situation and the value you are after is not a number - let's say it might have a character in it...the int.Parse will throw an Exception.
That is why I would do it like this:
string fullPSS1String = "PSS10000#001";
string afterPSS1 = fullPSS1String.Substring(4).TrimStart('0');
I am not being picky, just trying to think of all situations. I know that the first option would not throw an Exception...but I feel that doing it this way is more direct.
Related
I have a string with the format 00-00 and I want to increment it to 00-01.
Currently I am using Split() but I have the feeling that my approach is not really best practice.
I don't have to worry about edge cases and just want to know if there is an elegant solution.
Thanks
Linq approach without edge cases like 00-99 or 99-99
string input ="07-01";
string result = string.Join("-", input.Split('-')
.Select(int.Parse)
.Select((x, i) => (i == 1 ? ++x : x).ToString("00")));
Your method of utilizing string.Split() would be my suggestion too.
However, I'm wondering if you are repeatedly incrementing that number. if this is a one time action, then I agree with using the split method.
If you are continually incrementing this number (e.g. as a counter), you will start noticing that it takes more resources to do string operations (split) and conversions (string to int, int to string); compared to incrementing the value of the integer.
In this case, I would advocate that you keep the integer value in memory, and keep using that to generate your output string, instead of always having to start from scratch.
However, the latter suggestion only applies if you keep incrementing the same values. Your question did not specify that that is the case.
I have recently began to start learning C# and try to write a program that's similar to a calculator in a console. I've already done it with two integers and it worked. Now I am trying to write the code allowing more user inputs to calculate with.
The thing is, that I have stuck at spliting the string from the user-input. So let's say for example he writes:
1 + 2 * 3 - 5 I want to split it where the space happens. It should still be splitting when the user uses more than just one spaces in between. It's like the same as 1,2,,3,,,,5,6,,,4 : How can you split by the comma when there are MORE than one comma used? I only want the integers (and the operators from example 1).
I have already tried with [string_name].Split(' ') and [string_name].Split(',') but it only seems to ignore ONE char variable between the user-input-values I am interested in. That makes it impossible for me to put the values in an array and convert them to int.
Last question regarding my first example (1 + 2 * 3 - 5):
Besides accepting multiple spaces/comma, how can you split this string input efficiently, keeping int inputs and the operators? My idea was to save every uneven input value (1, 2, 3, 5) and every even input value (+, *, -,/) in an array each. I considered to put the operators into a switch with 4 cases and convert the string_array with numbers to integers. After that I would have put them all together into the exact same order like the user-input using for.
The thing is: Assuming I implement it correctly, I think that the calculation would be solved from left to right without considering the precedence of '*' and '/'.
Someone an idea how you can solve this problem with the "advanced" calculator efficiently? I have thought for a long time and tried all I could, but it doesn't seem to work ... Makes me sad a bit. I'd really like to solve this problem somehow.
Well the answer to your first question, you can pass an overload to Split that will ignore empty entries:
str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
So more traditionally, you'd want to parse the string entirely so you could handle things like parenthesis and the case where there is no space: 4*(1+2) for instance.
This is just to settle a curiosity - Suppose, in my C# project, I have a list containing millions of strings, each along the following lines:
"123Hi1234Howdy"
"Hi1Howdy23"
....
And all I need to know is, for each character in the string, if it is a digit or is it a letter.
So, I was thinking the easiest way to store this would be as 0's and 1's or True / False. So, in the example above, assuming I could assign IsLetter = 1 and IsDigit = 0, I could transform each line to:
"123Hi1234Howdy" >> 00011000011111
"Hi1Howdy23" >> 1101111100
....
That seems to me to be the most efficient way to store the data I'm looking for (but please do already correct me if I'm wrong on this - I'm still pretty much a newbie with programming).
So, writing the code that loops through a line and checks for whether each character is a digit or a letter and converting it to true/false or 1/0 is easy enough. My question is what would be the best way to store each line's output?
Should I store each line's output as a bit array? Could it be stored as some other type (maybe, say, integer) that could then be converted back to a series of bits? Should it be stored as a boolean array?
Any other thoughts on the best way to store this? When it's all said and done, I need to have a list where I can know, for example:
myList[0] = 00011000011111
myList[1] = 1101111100
And, then, therefore myList[0] <> myList[1]
You could use a BitArray for each word and set the bits to true or false if they are a digit or not. See this possible solution:
void Main()
{
string[] words =
{
"123Hi1234Howdy",
"Hi1Howdy23"
};
//Create an array of BitArray
var bArrays = words.Select(w => new BitArray(w.Select(c => char.IsDigit(c)).ToArray()));
//You can also create string too
var strings = words.Select(w => new string(w.Select(c => char.IsDigit(c) ? '1' : '0').ToArray())).ToArray();
}
This is not necessarily the fastest or most efficient. I guess it depends on what you intend to do with the strings, but at least it's simple!
I'm trying to make a calculator-like program where one would enter a calculation in a textbox and it would convert that calculation to an int with the result, here's what I have but it doesn't work much
string calcStr = textBox1.Text;
int result = calcStr;
Any suggestions that aren't too complicated?
If I understand the problem correct you want to be able to parse an expression like 1 + 3 + 4 from a textbox and execute a calculation based on the input. That is actually a harder task than one might think.
One common solution is to use the Shunting-yard algorithm to parse the expression. See http://en.wikipedia.org/wiki/Shunting-yard_algorithm for more details.
Use NCalc for this kind of job... it is free, comes with source and does all the heavy lifting (parse the mathematical expression etc.) and gives you the result of the calculation.
If you're trying to simply parse out the number from a string, use a function like
Int32.Parse(string)
If you need to take out an EQUATION, like
"3+4/2"
then you'll need to extract each character one at a time and determine what it is.
Like if the string was
"32+4/12"
You'd have to loop through every character in the string, and try to parse the current character into a number.
Theres a function to test if it's a number or not. or just check it's ascii value.
if it succeeds, take the current number plus the next one and try again until you hit a non-number character.
Now you can extract your numbers.
Characters that are not numbers are checked against the mathmatical operators you're allowing. Anything else throws an error.
Once you can extract all the whole equation, you'll probably have to do something like Stack operations to evaluate it. I believe in my Assembly class you'd push a buncha numbers and operators to the stack, and then pop it one at a top from the top, evaluating the previous number with the next number by the operator in between.
I hope this is what you were talking about. Best of luck!
The problem is with the convert of the txt box value, but why?
string strChar = strTest.Substring(0, Convert.ToInt16(txtBoxValue.Text));
Error is: Input string was not in a correct format.
Thanks all.
txtBoxValue.Text probably does not contain a valid int16.
A good way to avoid that error is to use .tryParse (.net 2.0 and up)
int subLength;
if(!int.TryParse(txtBoxValue.Text,out subLength)
subLength= 0;
string strChar = strTest.Substring(0, subLength);
This way, if txtBoxValue.Textdoes not contain a valid number then subLength will be set to 0;
One thing you may want to try is using TryParse
Int16 myInt16;
if(Int16.TryParse(myString, out myInt16)
{
string strChar = strTest.Substring(0, myInt16);
}
else
{
MessageBox.Show("Hey this isn't an Int16!");
}
A couple reasons the code could be faulty.
To really nail it down, put your short conversion on a new line, like this:
short val = Convert.ToInt16(txtBoxValue.Text);
string strChar = strTest.Substring(0, val);
Likely the value in txtBoxValue.Text is not a short (it might be too big, or have alpha characters in it). If it is valid and val gets assigned, then strTest might not have enough characters in it for substring to work, although this normally returns a different error. Also, the second parameter of substring might require an int (not sure, can't test right now) so you may need to actually convert to int32 instead of 16.
What is the value of txtBoxValue.Text during your tests?
ASP.NET offers several validation controls for checking user input. You should use something like a CompareValidator or RegularExpressionValiditor in your WebForm if you're expecting a specific type of input, eg, an Integer.