Write A Program To Count The Sum Of Numbers In A String In C
Extracting numerical values embedded within a string and calculating their sum is a common task in programming, useful for data parsing and validation. In this article, you will learn how to implement a C program to identify and sum all numbers present in a given string.
Problem Statement
The challenge is to process a string that may contain a mix of alphabetic characters, special symbols, and digits. The goal is to accurately identify sequences of digits as distinct numbers, convert them into their integer equivalents, and then compute the total sum of these numbers. For example, given a string like "abc12def34gh", the program should identify 12 and 34, and output their sum, which is 46. This problem often arises when parsing log files, user input, or custom data formats where numerical data is intertwined with descriptive text.
Example
Consider the input string: "The price is $12.50, and you saved $3.00 today. Total: $15.50"
If we consider only whole numbers for summation, the expected numbers are 12, 50, 3, 00, 15, 50.
The sum of these numbers (12 + 50 + 3 + 00 + 15 + 50) would be 130.
*Note: For simplicity, our C program will focus on integer sums and ignore decimal points unless explicitly programmed to parse floats.*
Background & Knowledge Prerequisites
To understand and implement the solution, readers should be familiar with:
- C Language Basics: Variables, data types, loops (for, while), conditional statements (if-else).
- String Manipulation: Understanding how strings are represented in C (null-terminated character arrays).
- Character Functions: Basic usage of functions from
likeisdigit(). - ASCII Values: Knowledge that characters have corresponding integer ASCII values, which is key for converting digit characters to integer values (e.g.,
'5' - '0'results in5).
Use Cases or Case Studies
This problem has several practical applications across various domains:
- Log File Analysis: Extracting error codes, transaction IDs, or performance metrics embedded in system log entries.
- User Input Processing: Validating and extracting numerical data from user-provided text, like "I want 5 apples and 2 oranges."
- Configuration File Parsing: Reading numerical settings (e.g., port numbers, retry counts) from human-readable configuration files.
- Data Cleaning: Extracting specific numerical values from unstructured text data before further analysis.
- Simple Calculators: Building a basic parser that can sum numbers found in a mathematical expression string.
Solution Approaches
We will focus on a robust and easy-to-understand approach involving iterating through the string character by character.
Approach 1: Iterating and Manual Number Conversion
This approach involves traversing the string, identifying digit sequences, converting them into integers, and accumulating their sum.
Summary: Scan the string character by character. When a digit is found, build the number until a non-digit is encountered, then add it to the total sum. Reset for the next number.
Code Example:
// Sum Numbers in String
#include <stdio.h> // Required for printf
#include <string.h> // Required for strlen
#include <ctype.h> // Required for isdigit
int sumNumbersInString(const char *str) {
int totalSum = 0;
int currentNumber = 0;
int i = 0;
// Step 1: Iterate through the string character by character
while (str[i] != '\\0') {
// Step 2: Check if the current character is a digit
if (isdigit(str[i])) {
// Step 3: Build the current number by processing consecutive digits
currentNumber = currentNumber * 10 + (str[i] - '0');
} else {
// Step 4: If a non-digit is found, add the accumulated currentNumber to totalSum
// Then reset currentNumber for the next potential number
totalSum += currentNumber;
currentNumber = 0;
}
i++; // Move to the next character
}
// Step 5: After the loop, add the last accumulated number (if any) to totalSum
// This handles cases where the string ends with a number
totalSum += currentNumber;
return totalSum;
}
int main() {
// Test Case 1: String with numbers, letters, and symbols
const char *testString1 = "abc12def3ghi45jkl";
printf("String: \\"%s\\"\\n", testString1);
printf("Sum of numbers: %d\\n\\n", sumNumbersInString(testString1));
// Test Case 2: String with only numbers
const char *testString2 = "12345";
printf("String: \\"%s\\"\\n", testString2);
printf("Sum of numbers: %d\\n\\n", sumNumbersInString(testString2));
// Test Case 3: String with no numbers
const char *testString3 = "HelloWorld";
printf("String: \\"%s\\"\\n", testString3);
printf("Sum of numbers: %d\\n\\n", sumNumbersInString(testString3));
// Test Case 4: String with numbers at the beginning and end
const char *testString4 = "7apples and 10bananas cost 17dollars";
printf("String: \\"%s\\"\\n", testString4);
printf("Sum of numbers: %d\\n\\n", sumNumbersInString(testString4));
// Test Case 5: Empty string
const char *testString5 = "";
printf("String: \\"%s\\"\\n", testString5);
printf("Sum of numbers: %d\\n\\n", sumNumbersInString(testString5));
// Test Case 6: String with zero
const char *testString6 = "The temperature is 0 degrees";
printf("String: \\"%s\\"\\n", testString6);
printf("Sum of numbers: %d\\n\\n", sumNumbersInString(testString6));
return 0;
}
Sample Output:
String: "abc12def3ghi45jkl"
Sum of numbers: 60
String: "12345"
Sum of numbers: 12345
String: "HelloWorld"
Sum of numbers: 0
String: "7apples and 10bananas cost 17dollars"
Sum of numbers: 34
String: ""
Sum of numbers: 0
String: "The temperature is 0 degrees"
Sum of numbers: 0
Stepwise Explanation:
- Initialization:
-
totalSum: An integer variable initialized to0to store the cumulative sum of numbers found.
-
currentNumber: An integer variable initialized to 0 to build each number as digits are encountered.i: An integer variable initialized to 0 as an index to iterate through the string.- String Traversal: A
whileloop iterates through the input stringstruntil the null terminator (\0) is reached. - Digit Check: Inside the loop,
isdigit(str[i])checks if the character at the current indexiis a digit. - Number Building:
- If
str[i]is a digit, it contributes tocurrentNumber. The logiccurrentNumber = currentNumber * 10 + (str[i] - '0')effectively converts the character digit to its integer value (str[i] - '0') and appends it tocurrentNumber. For example, ifcurrentNumberis1andstr[i]is'2',currentNumberbecomes1 * 10 + 2 = 12.
- If
- Number Completion and Summation:
- If
str[i]is *not* a digit, it means a sequence of digits forming a number has just ended (or no digits were found).
- If
currentNumber (if it's greater than 0, meaning a number was built) is added to totalSum.currentNumber is then reset to 0, preparing for the next potential number sequence.- Handling End of String: After the
whileloop finishes, there's a final check:totalSum += currentNumber;. This is crucial because if the string ends with a number (e.g., "abc123"), the lastcurrentNumberwouldn't have been added tototalSumby theelseblock. This line ensures that such numbers are included in the final sum. - Return Value: The function returns the
totalSum.
Conclusion
Successfully extracting and summing numbers embedded in a string in C involves careful iteration and character handling. The manual iteration approach provides a clear, step-by-step method to build numbers from digit sequences and accumulate their sum. This technique is fundamental for various data processing tasks where numerical data needs to be isolated from mixed text content.
Summary
- The problem involves identifying digit sequences in a string, converting them to integers, and calculating their total sum.
- Key C libraries like
(forisdigit) are essential for character classification. - A
whileloop iterates through the string, buildingcurrentNumberwhen digits are found. - Non-digit characters trigger the addition of
currentNumbertototalSumand resetcurrentNumber. - A final check after the loop ensures numbers at the end of the string are included in the
totalSum. - This approach is robust for handling strings with no numbers, only numbers, or numbers interspersed with other characters.