Convert a String to Integer Array in C/C++
Last Updated :
14 Jun, 2023
Given a string str containing numbers separated with ", ". The task is to convert it into an integer array and find the sum of that array. Examples:
Input : str = "2, 6, 3, 14"
Output : arr[] = {2, 6, 3, 14}
Sum of the array is = 2 + 6 + 3 + 14 = 25
Input : str = "125, 4, 24, 5543, 111"
Output : arr[] = {125, 4, 24, 5543, 111}
Approach:
- Create an empty array with size as string length and initialize all of the elements of array to zero.
- Start traversing the string.
- Check if the character at the current index in the string is a comma(,). If yes then, increment the index of the array to point to the next element of array.
- Else, keep traversing the string until a ',' operator is found and keep converting the characters to number and store at the current array element. To convert characters to number:
arr[j] = arr[j] * 10 + (Str[i] - 48)
Below is the implementation of the above idea:
CPP
// C++ program to convert a string to
// integer array
#include <bits/stdc++.h>;
using namespace std;
// Function to convert a string to
// integer array
void convertStrtoArr(string str)
{
// get length of string str
int str_length = str.length();
// create an array with size as string
// length and initialize with 0
int arr[str_length] = { 0 };
int j = 0, i, sum = 0;
// Traverse the string
for (i = 0; i<str.length(); i++) {
// if str[i] is ', ' then split
if (str[i] == ',')
continue;
if (str[i] == ' '){
// Increment j to point to next
// array location
j++;
}
else {
// subtract str[i] by 48 to convert it to int
// Generate number by multiplying 10 and adding
// (int)(str[i])
arr[j] = arr[j] * 10 + (str[i] - 48);
}
}
cout<<"arr[] ";
for (i = 0; i <= j; i++) {
cout << arr[i] << " ";
sum += arr[i]; // sum of array
}
cout<<endl;
// print sum of array
cout<<sum<<endl;
}
// Driver code
int main()
{
string str = "2, 6, 3, 14";
convertStrtoArr(str);
return 0;
}
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(N), Where N is the length of the string
Approach : Using Regular Expressions and Mapping
Below is the implementation of the above approach:
C++
// C++ program of the above approach
#include <iostream>
#include <numeric>
#include <regex>
#include <vector>
std::pair<std::vector<int>, int>
convertAndSum(const std::string& str)
{
std::vector<int> arr;
// Extract all the numbers using regular
// expressions
std::regex pattern("\\d+");
std::sregex_iterator it(str.begin(), str.end(),
pattern);
std::sregex_iterator end;
while (it != end) {
// Convert the extracted number into an
// integer and add it to the array
arr.push_back(std::stoi(it->str()));
++it;
}
// Calculate the sum of the array
int arraySum
= std::accumulate(arr.begin(), arr.end(), 0);
return { arr, arraySum };
}
// Driver Code
int main()
{
std::string str = "2, 6, 3, 14";
auto result = convertAndSum(str);
std::cout << "arr[] = ";
for (int num : result.first) {
std::cout << num << " ";
}
std::cout << std::endl;
std::cout << "Sum of array is = " << result.second
<< std::endl;
return 0;
}
Outputarr[] = 2 6 3 14
Sum of array is = 25
Time Complexity: O(N), where N is the length of the input string.
Auxiliary Space: O(M), where M is the number of numbers in the input string.
Similar Reads
Convert given Array of Integers into Words Given an array arr[] of N elements which are in range [0, 9]. the task is to convert each array element into its numeric strings. Examples: Input: arr[] = [1, 4, 3, 2, 6]Output: one four three two six Input: arr[]= [0, 4, 4, 6, 9]Output: zero four four six nine Approach: The problem can be solved wi
4 min read
Convert std::string to LPCWSTR in C++ C++ provides us a facility using which one can represent a sequence of characters as an object of a class. This class is std::string. Internally, std::string class represents a string as a sequence of characters (bytes) and each character can be accessed using the [] operator. The difference between
2 min read
Convert given Binary Array to String in C++ with Examples Given a binary array arr[] containing N integer elements, the task is to create a string s which contains all N elements at the same indices as they were in array arr[]. Example: Input: arr[] = {0, 1, 0, 1}Output: string = "0101" Input: arr[] = { 1, 1, 0, 0, 1, 1}Output: string = "110011" Different
6 min read
Extract all integers from string in C++ Given a string, extract all integers words from it. Examples : Input : str = "geeksforgeeks 12 13 practice" Output : 12 13 Input : str = "1: Prakhar Agrawal, 2: Manish Kumar Rai, 3: Rishabh Gupta" Output : 1 2 3 Input : str = "Ankit sleeps at 4 am." Output : 4 The idea is to use stringstream:, objec
2 min read
How to split a string in C/C++, Python and Java? Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter. In C: // Splits str[] according to given delim
7 min read