![]() |
VOOZH | about |
Sometimes, while working with Strings, we may need to perform the split operation. The straightforward split is easy. But sometimes, we may have a problem in which we need to perform split on certain characters but have exceptions. This discusses split on comma, with the exception that comma should not be enclosed by brackets. Lets discuss certain ways in which this task can be performed.
Method #1: Using loop + strip() This is brute force way in which we perform this task. In this we construct each element of list as words in String accounting for brackets and comma to perform split.
The original string is : gfg, is, (best, for), geeks The string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']
Method #2: Using regex() This is yet another way in which this task can be performed. In this, we use a regex instead of manual brute force logic for brackets comma and omit that from getting split.
The original string is : gfg, is, (best, for), geeks The string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using str.split() and list comprehension
The original string is : gfg, is, (best, for), geeks The string after exceptional split : ['gfg', 'is', '(best', 'for)', 'geeks']
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.