Home > Net >  Iterate a string until int or char
Iterate a string until int or char

Time:10-11

I want to make to two vectors from a string.

from :

std::string input = "82aw55beA1/de50Ie109 500s";

to :

std::vector<int> numbers = {82,55,1,50,109,500};
std::vector<char> notNumbers = {'a','w','b','e','A','/','d','e','I','e',' ','s'};

How do I do this in the most efficient time complexitie?

CodePudding user response:

You can make one pass over the string. You need to know if you're currently parsing a digit or not, whether you're "in" a number, and the current number you're in.

It's a pretty straightforward process, but if you have questions, please ask.

#include <string>
#include <vector>
#include <iostream>
#include <cctype>

int main() {
    std::string input = "82aw55beA1/de50Ie109 500s";

    std::vector<int> numbers;
    std::vector<char> notNumbers;

    int currentNumber = 0;
    bool inNumber = false;

    for (auto ch : input) {
        if (std::isdigit(ch)) {
            if (!inNumber) {
                currentNumber = 0;
                inNumber = true;
            }
  
            currentNumber = currentNumber * 10   (ch - '0');
        }
        else {
            if (inNumber) {
                numbers.push_back(currentNumber);
                inNumber = false;
            }
 
            notNumbers.push_back(ch);
        }
    }

    if (inNumber) {
        numbers.push_back(currentNumber);
    }

    for (auto i : numbers) {
        std::cout << i << std::endl;
    }

    for (auto ch : notNumbers) {
        std::cout << ch << std::endl;
    }
}
  • Related