Convert a String to Integer Array in C/C++

In C, converting a comma-separated string to an integer array involves parsing the string character by character and extracting numeric values. This process requires traversing the string, identifying delimiters (commas), and converting individual number substrings to integers.

Syntax

// Function to convert string to integer array
void convertStringToArray(char str[], int arr[], int *size);

Example: Using Character-by-Character Parsing

This approach traverses the string and builds integers by accumulating digits until a comma is encountered −

#include <stdio.h>
#include <string.h>

void convertStringToArray(char str[], int arr[], int *size) {
    int i = 0, j = 0, num = 0;
    int len = strlen(str);
    
    for (i = 0; i <= len; i++) {
        // If current character is digit
        if (str[i] >= '0' && str[i] <= '9') {
            num = num * 10 + (str[i] - '0');
        }
        // If comma or end of string
        else if (str[i] == ',' || str[i] == '\0') {
            arr[j] = num;
            j++;
            num = 0;
        }
        // Skip spaces
    }
    *size = j;
}

int main() {
    char str[] = "2, 6, 3, 14";
    int arr[100];
    int size = 0;
    int i, sum = 0;
    
    convertStringToArray(str, arr, &size);
    
    printf("arr[] = ");
    for (i = 0; i < size; i++) {
        printf("%d ", arr[i]);
        sum += arr[i];
    }
    printf("\nSum of array is = %d\n", sum);
    
    return 0;
}
arr[] = 2 6 3 14 
Sum of array is = 25

Example: Using strtok() Function

An alternative approach using the standard library function strtok() for tokenization −

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char str[] = "10, 25, 30, 45";
    char *token;
    int arr[100];
    int size = 0, i, sum = 0;
    
    // Get first token
    token = strtok(str, ",");
    
    // Parse all tokens
    while (token != NULL) {
        arr[size] = atoi(token);
        size++;
        token = strtok(NULL, ",");
    }
    
    printf("arr[] = ");
    for (i = 0; i < size; i++) {
        printf("%d ", arr[i]);
        sum += arr[i];
    }
    printf("\nSum of array is = %d\n", sum);
    
    return 0;
}
arr[] = 10 25 30 45 
Sum of array is = 110

Key Points

  • The manual parsing method gives more control over the conversion process.
  • strtok() modifies the original string, so use a copy if needed.
  • atoi() automatically handles leading/trailing whitespace in tokens.
  • Always validate array bounds to prevent buffer overflow.

Conclusion

Converting a comma-separated string to integer array in C can be done using manual character parsing or library functions like strtok(). The manual approach offers more flexibility while strtok() provides simpler tokenization.

Updated on: 2026-03-15T12:45:21+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements