Home > Software engineering >  how to remove redundant whitespaces without using functions
how to remove redundant whitespaces without using functions

Time:12-02

I need to remove redundant whitespaces from string without using any function like split(), strip() and so on. I have string like

" apples   bananas orange  "

and I need

"apples bananas orange".

So far I am here:

string = " apples   bananas orange  "
result = ""
output = ""
i = 0
while i < len(string):
    result = ""
    while string[i] != " ":
        result  = string[i]
        i  = 1
    while string[i] == " ":
        i  = 1
        if i >= len(string):
            break
    output  = result   " "

print(output)

But now I can not get rid of whitespaces on both sides.

I was also trying to get rid of whitespaces using just one cycle, but I am not able to add one whitespace between words.

Thanks in advance for any help.

CodePudding user response:

Without any function, even len:

txt = " apples   bananas orange  "
out = ''
p = ' '  # the previous character

for c in txt:  # the current character
    if c == ' ' and p == ' ':  # continue if two consecutive white space
        continue
    p = c  # remember the current character for the next iteration
    out  = c  # add the current character to the result

# remove the last character if remain a trailing white space
out = out if out and out[-1] != ' ' else out[:-1]

Output:

>>> out
'apples bananas orange'

CodePudding user response:

I think this would work in O(n):

s = " apples   bananas orange  "
s = s   ' '
i, j = 0, 0
out_str = ''
while j < len(s):
    if s[i] == ' ':
        i  = 1
        j  = 1
    elif s[j] != ' ':
        j  = 1
    else:
        out_str  = s[i:j]   ' '
        j = j   1
        i = j
out_str = out_str[:-1]
out_str

CodePudding user response:

Pretty hard to not use any sort of function.

Here is some code which doesn't use a function

s = " apples   bananas orange  "

# Remove start and end spaces
if s[0] == " ":
    s = s[1:]
if s[-1] == " ":
    s = s[:-1]
    
new_s = []
for i, c in enumerate(s[:-1]):
    if not (c == ' ' and s[i 1] == ' '):
        new_s.append(c)
print(''.join(new_s))

Technically ''join() is a string-class function but if they tell you not to use that in python then they are wrong. This is python, not C.

CodePudding user response:

using stacks

def func(string):
    stack = []
    for i,v in enumerate(string):
        if (not stack and v==' ') or (stack and stack[-1]==' ' and v==' '):
            pass
        else:
            stack.append(v)
    if stack[-1]==' ':
        stack = stack[:-1]
    return ''.join(stack)
  • Related