C Online Compiler
Example: Sum Numbers in String in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// 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; }
Output
Clear
ADVERTISEMENTS