Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Assume I let user input number : 1298743257884834...(long as user need)
Let program tell how many digit are they ?
then give result by SUM them = ?
By using LINQ
string input = // get input from console, textbox, ...
int inputLength = input.Length; // get number of digits, although you don't need it here
int sum = input.Sum(c => int.Parse(c.ToString())); // summarize
Hint: use the BigInteger structure found in System.Numerics.
First of all you can know the number of digits in this way:
string digits = TextBox1.Text;
long digitsnumber = digits.Length;
Then to sum each number, you need to loop in your string like an array of char, in this way, and cast the car value to an integer with the GetNumericValue method of System.Char:
int sum = 0;
foreach (var c in digits)
{
if (Char.IsNumber(c))
{
sum += (int)Char.GetNumericValue(c);
}
}
Sum will be your result.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I need to count sum of the numbers found in a string, not digits. For example, there are string = "abc12df34", and the answer must be 46 (12+34), not 10. Also maybe negative numbers for string = "abc10gf-5h1" answer must be 6. I can not understand how to implement this.
RegEx approach:
string input = "abc10gf-5h1";
int result = Regex.Matches(input, "-?[0-9]+").Cast<Match>().Sum(x =>int.Parse(x.Value));
While the above answer is elegant, it's not really something to understand what to do or how to approach the problem. Here is another, more explicit solution.
In words, you iterate through your string, collect digits as long as there are any, if you find a nondigit, your number is finished, you convert the number to integer and sum it up, clear the number string. The same you do if you find the end of the string. On the next found digit you start collecting digits again.
This algorithm will fail on any number larger than than 10 digits in multiple ways (as the other answer will also), but this is just for demonstration anyway.
string input = "abc10gf-5-1h1";
var number = new char[10];
int numberlength = 0;
int pos = 0;
int sum = 0;
while (pos < input.Length)
{
char c = input[pos++];
if (char.IsDigit(c))
{
number[numberlength++]=c;
}
else
{
if (numberlength > 0)
{
sum += int.Parse(new String(number, 0, numberlength));
numberlength = 0;
}
if (c=='-')
number[numberlength++]=c;
}
}
if (numberlength > 0)
sum += int.Parse(new String(number, 0, numberlength));
Console.WriteLine(sum);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to create a grade calculator but I'm completely unsure how to compile the code to do so.
So far I've got the ability to split a user's response, but now I need to know how to take those splits and use them as separate values in order to create an average. I'm completely clueless how to achieve this and I've been searching for 2 days now on the internet with no luck.
Console.WriteLine ("User response seperated by commas goes here.");
string response = Console.ReadLine ();
Char delimiter = ',';
string[] splitResponses = response.Split (delimiter);
I need to know how to take those splits and use them as separate
values in order to create an average.
Not sure what you mean by take those splits and use them as separate
values, result is an array you could elements using index like splitResponseses[0]
To calculate the average you need to convert them to ints (or respective types), and calculate average.
string[] splitResponses = response.Split (delimiter); // Split string
int sum=0;
foreach(string s in splitResponses)
{
var valueInt = int.Parse(s); // convert string to an int.
sum+= valueInt;
}
double average = (double)sum/splitResponses.Length;
Another simple solution using Linq extensions.
int[] splitResponses = response.Split (delimiter) // Split string
.Select(int.Parse) // Convert To int value;
.ToArray();
Now you could calculate average using
splitResponses.Average(); // Average
splitResponses.Sum(); // Sum
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I can't figure out why the code is in the wrong format. I'm getting the the error on the line of TotalTicketprice = decimal.Parse(overallTicketCostlabel.Text); and everything that's associated with it. Anyone know a solution for this?
private void calculateButton_Click(object sender, EventArgs e)
{
int Tickets; //Quantity of Tickets
decimal Price; //price per ticket
decimal DiscountPercent = 0.1m; // Discount given
decimal TotalTicketprice; //Ticket price before discount given
decimal Discount;
Tickets = int.Parse(ticketQuantityTextBox.Text);
Price = decimal.Parse(priceTicketTextBox.Text);
TotalTicketprice = decimal.Parse(overallTicketCostlabel.Text);
Discount = decimal.Parse(initialDiscountLabel.Text);
//Ticket Price
overallTicketCostlabel.Text = (Price * Tickets).ToString("c");
//Displays Discount
initialDiscountLabel.Text = (TotalTicketprice * DiscountPercent).ToString("c");
//Displays Discounted Total Cost
discountedCostLabel.Text = (TotalTicketprice - Discount).ToString("c");
Just a guess, going from your naming convention, should this be;
TotalTicketprice = decimal.Parse(overallTicketCostTextBox.Text);
instead of:
TotalTicketprice = decimal.Parse(overallTicketCostlabel.Text);
You may also want to include some validation to ensure that these are numeric prior to parsing them.
overallTicketCostlabel.Text = (Price * Tickets).ToString("c");
this formats as a Currency. This means that it will probably have a currency symbol in the text. Like $ 100 for example.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The problem, i am facing in this code is that first iteration of loop is good but in second iteration when i press y program gives error.
Error = Input string was not in a correct format.
Line of Error = my = int.Parse(Console.ReadLine());
static void Main(string[] args)
{
int a, my;
char again = 'y';
while ((again == 'y' || again=='Y'))
{
Console.Write("Enter the value for your number = ");
my = int.Parse(Console.ReadLine());
Random b = new Random();
a = b.Next(1, 6);
if (a == my)
{
Console.WriteLine("Congratulations");
}
else
{
Console.WriteLine("you Lost");
Console.WriteLine("My no is {0}.", a);
}
Console.Write("Again? Then press 'y' or 'Y' = ");
again = (char)Console.Read();
}
Console.ReadLine();
}
Change
again = (char)Console.Read();
to
again = (char)Console.ReadLine().First();
Console.Read Reads the next character from the standard input stream. To continue you press a key ('y' in this case) and press 'enter'. Which means you input 2 characters and read 1. Which one is read by next Console.Readline. So, you never get the actual string in this line
my = int.Parse(Console.ReadLine());
Rather you get the character you did not read previously. And this one can not be parsed to integer.
If you got Input string was not in a correct format in a Int32.Parse, try replace it for a Int32.TryParse
Int32.TryParse(Console.ReadLine(), out my);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm having a mind melt.
The problem I'm having is that I need to be able to do the following:
I have an input that defines how many wildcards I can use UP TO, in this example we say 2.
I have a string, ABCDEFGH.
I need to create an array of all the different ways those 2 wildcards can feature in the string so that I can feed it into an SQL query.
By hand we can do.
_BCDEFGH
A_CDEFGH
AB_DEFGH
ABC_EFGH
ABCD_FGH
ABCDE_GH
ABCDEF_H
ABCDEFG_
And using our limit of 2.
__CDEFGH
_B_DEFGH
_BC_EFGH
_BCD_FGH
_BCDE_GH
_BCDEF_H
_BCDEFG_
A__DEFGH
A_C_EFGH
A_CD_FGH
A_CDE_GH
A_CDEF_H
A_CDEFG_
AB__EFGH
AB_D_FGH
and so on...
For compatability with SQL I need to use the wildcard character as an underscore_.
Can someone help me understand how to structure my loops? Bare in mind that limit of wildcards isn't always 2, it is a variable.
This isn't a question of Regex or matching, I need to be able to create these variations of a string.
you get something like this
List<String> permutations(String original, int numberOfWildcards) {
//add 1 more wildcard to each posible position in the original string
List<String> perm = new List<String>();
for (int i = 0; i < original.Length; ++i)
{
if (original[i] != '_')
perm.Add(original.Substring(0, i) + "_" + original.Substring(i + 1, original.Length));
}
if ( numberOfWildcards == 1)
{
return perm;
}
//now if we need to search deeper we recusively do this for each substring
List<String> permWithMoreWildmark = new List<String>();
foreach (var str in perm)
{
permWithMoreWildmark.AddRange(permutations(str,numberOfWildcards-1));
}
return permWithMoreWildmark;
}
the trick is to try to solve the problem for 1 deep first and then try to figure out the recursion