how to remove sub string from string without using any functions

Question:

I have text

abcdblobefgblobhijk

How to remove the substring blob from the string without using any in built functions which provide 1 line solution like String.replace etc. In other words program should get the string as input and without using any inbuilt function should output the string without substring “blob”.

Asked By: Udhai kumar

||

Answers:

I tried to do it as “manually” as possible, without any shortcuts or python tricks,

I hope this helps in any way:

text = "abcdblobefgblobhijk"
sub = "blob"

new_text =''
i=0
last_i = 0
while i <  len(text):
    if text[i:i+len(sub)] == sub:
        new_text += text[last_i:i]
        last_i=i+len(sub)
        i=i+len(sub)
    else:
        i+=1
new_text += text[last_i:i]

print(new_text)

Answered By: Adam.Er8
def remove(string, substr):
    newstring = ''
    flag = 0
    str_length = len(string)
    substr_length = len(substr)
    for i in range(str_length):
        if string[i] == substr[0]:
            end = i + substr_length
            temp = string[i:end]
            if substr == temp: 
                return string[:i] + string[end:]
    return string
print(remove("Dhaval Dhanesha","sha"))

Output : Dhaval Dhane

Answered By: Dhaval Dhanesha
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.