440,581 Members | 1,990 Online Need help? Post your question and get tips & solutions from a community of 440,581 IT Pros & Developers. It's quick & easy.

# extracting integer from the given string

 P: 2 question: the program must accept a string s as intput.the program must print the sum of all two or three digit numbers present in the string s as output. input: i got up at 10:100am and went to college at 12222:50 10 pm output: 10+100+50+10=170 how can i extract the integers from the given string?? 1 Week Ago #1
5 Replies

 100+ P: 147 A string of input is provided by the user. To extract the numbers from the string we can scan every character from the string and compare it with the numeric values. If the character is a digit, we can keep copying it to a temporary character array. Stop this process once a non-digit character is found. By this, we would have the number in the temporary character array. After that conversion from string to int can be done using the library function int atoi(const char *str). This process can be repeated for each number present in the string. For the addition of the values, take a variable sum with the initial value of 0. And the expression sum=sum+temporary_var can be used to keep adding those values. 1 Week Ago #2

 P: 30 A simple loop will manage this: Expand|Select|Wrap|Line Numbers string input = "I got up at 10:100am and went to college at 12222:50 10 pm";   string digits = string.Empty; int total = 0; bool first = true; foreach (char character in (input + " ")) {     if (!Char.IsDigit(character))     {                 if (digits.Length > 0 && digits.Length <=3)         {             if (!first)             {                 Console.Write("+");             }             Console.Write(digits);             total += Convert.ToInt32(digits);             first = false;         }         digits=string.Empty;     }     else     {         digits += character;     } } Console.WriteLine("=" + total.ToString()); 1 Week Ago #3

 P: 2 Thanks sir,its clear to me but I want some c code examples for comparision of numeric values and finding the digit 1 Week Ago #4

 100+ P: 147 @cactusdata The question is asked in the C/C++ category, not in the C sharp one. It would have benefitted the user if you had posted the algorithm/approach instead. It doesn't even make more sense when the solution is to be implemented in C language, where there is no concept of classes and whole object-oriented programming stuff. @Iniya What have you done so far? Comparisons are simple using the if statements. Expand|Select|Wrap|Line Numbers if(string_name[index]=='1'){ ... }   1 Week Ago #5

 P: 30 Missed the C/C++, sorry, but my C# code should be easy to convert. 1 Week Ago #6 