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
#include <bits/stdc++.h>;
using namespace std;
void convertStrtoArr(string str)
{
int str_length = str.length();
int arr[str_length] = { 0 };
int j = 0, i, sum = 0;
for (i = 0; i<str.length(); i++) {
if (str[i] == ',' )
continue ;
if (str[i] == ' ' ){
j++;
}
else {
arr[j] = arr[j] * 10 + (str[i] - 48);
}
}
cout<< "arr[] " ;
for (i = 0; i <= j; i++) {
cout << arr[i] << " " ;
sum += arr[i];
}
cout<<endl;
cout<<sum<<endl;
}
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++
#include <iostream>
#include <numeric>
#include <regex>
#include <vector>
std::pair<std::vector< int >, int >
convertAndSum( const std::string& str)
{
std::vector< int > arr;
std::regex pattern( "\\d+" );
std::sregex_iterator it(str.begin(), str.end(),
pattern);
std::sregex_iterator end;
while (it != end) {
arr.push_back(std::stoi(it->str()));
++it;
}
int arraySum
= std::accumulate(arr.begin(), arr.end(), 0);
return { arr, arraySum };
}
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;
}
|
Output
arr[] = 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.
Share your thoughts in the comments
Please Login to comment...