Udhai kumar
Udhai kumar

Reputation: 43

how to remove sub string from string without using any functions

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".

Upvotes: 0

Views: 1812

Answers (2)

Dhaval Dhanesha
Dhaval Dhanesha

Reputation: 1

def remove(string, substr):
    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

Upvotes: 0

Adam.Er8
Adam.Er8

Reputation: 13413

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)

Upvotes: 4

Related Questions