Monday, April 20, 2015

convert spaces to %20

Convert spaces to %20 in buffer with spaces at end.
"this.is.a.test......"
"this%20is%20a%20test"
Test cases:
".test.."
"%20test"

"test..."
"test%20"

"..."
"%20"

"........."
"%20%20%20"

throw exception for:
"...test"
"..test."
3 passes: count spaces, verify actual spaces, convert spaces.

Throw if
- spaces %3 is not 0
- the spaces aren't within actual length.
convert-spaces(s):
    spaces = countspaces(s)
    if spaces == 0:
        return
    i = s.length()-1 - (spaces*2)
    target = s.length()-1
    while i >= 0:
        if s[i] == ' ':
            s[target-2] = '%'
            s[target-1] = '2'
            s[target-0] = '0'
            target -= 2
        else:
            s[target] = s[i]
        i--
        target--

countspaces(s):
    spaces = 0
    // verify total spaces count
    for c in s:
        if c == ' ':
            spaces++
    if spaces % 3 != 0:
        throw
    spaces /= 3
    // verify if spaces are within actual length
    actuallength = s.length() -(spaces *2)
    for i = 0, i < actuallength, i++:
        scount++
    if scount != spaces:
        throw
    return spaces

No comments:

Post a Comment