Search code examples
splitpseudocode

Split string by comma where comma is also a element without RegExp


I have to create an Alphabet or Range base on a given string, i.e., new Alphabet('ax, b,c, d') where ax, b, c, d will be part of the alphabet elements list, I have to split the given string with commas as a delimiter, but , also can be an element so you could do new Alphabet(',, {, }, [, ]'). The main problem is that I should not use RegExp to solve the pattern matching. White Space between elements and the previous comma is optional, so they can not be used as a delimiter.

I've tried to think about a solution to solve the pattern matching but I'm not capable to see a solution where RegExp does not include.

It would be great if some could help me with some pseudo-code explaining a solution.


Solution

  • Alright so this will look similar to python/Typescript and be pretty rough. From my understanding you are breaking out the components of the string into an array based off of comas. If you know how to use RegEx you could just code that into a for loop (food for thought). Anyways here it is:

    function makeAlphabet(string):
        charArray = [] // for storing alphabet
        sequence = []  // for storing symbol like 'ax'
        len = length(string)
        for( i=0, i < len, i++):
            char = string[i]
            // we hit comma and our sequence exists or we are at the end of the array
            if(char == ',' && length(sequence) > 0 || i == (len - 1)):
                // add char sequence to array 
                charArray.append(sequence)
                sequence = []
            else:
                sequence.append(char)
        return charArray
    

    This will return an array of arrays of characters that represent each element. You could make the inner array a string if that is what you need. The logic essentially checks to see if we have any previous characters if we find a comma. If that is the case it adds the sequence to the array otherwise it adds the comma to the sequence.