Home > Software design >  program needs to process data with spaces and strings and need to add underscore in strings
program needs to process data with spaces and strings and need to add underscore in strings

Time:10-27

Kinda confuse how to solve this one. Like each inversion between letters will be added a pause using the character "_", but this does not apply if there are spaces. There is a ReverseString function with a str parameter of type string which will be the input character data to be reversed.

package main

import "fmt"

func ReverseString(str string) string {
    r := ""
    for i := len(str) - 1; i >= 0; i-- {
        if str[i] >= 0 && string(str[i]) != " " {
            r  = string(str[i])   "_"
        }
    }
    return string(r)
}

func main() {
    fmt.Println(ReverseString("hello world"))
    fmt.Println(ReverseString("i am a student"))
}
var _ = Describe("ReverseString", func() {
    When("input str contains 'Hello World'", func() {
        It("should return 'd_l_r_o_W o_l_l_e_H'", func() {
            Expect(main.ReverseString("Hello World")).To(Equal("d_l_r_o_W o_l_l_e_H"))
        })
    })

CodePudding user response:

Here is one option

func ReverseString(s string) string {
    // split string into array
    sarr := strings.Split(s, "")
    
    // reverse the string array
    for i, j := 0, len(sarr)-1; i < j; i, j = i 1, j-1 {
        sarr[i], sarr[j] = sarr[j], sarr[i]
    }
    // join with underscore
    nstr := strings.Join(sarr, "_")
    // remove the space
    return strings.ReplaceAll(nstr, "_ _", " ") 
}

CodePudding user response:

You are assuming that the string only contains ASCII characters. A Go string typically contains UTF-8 encoded characters (Unicode code points).

package main

import "fmt"

func ReverseString(s string) string {
    us := []rune(s)
    rs := make([]rune, 2*len(us))
    j := len(rs)
    for i, r := range us {
        j--
        rs[j] = r
        if r != ' ' {
            if i 1 < len(us) && us[i 1] != ' ' {
                j--
                rs[j] = '_'
            }
        }
    }
    return string(rs[j:])
}

func main() {
    hello := "hello world"
    fmt.Printf("%q\n", hello)
    fmt.Printf("%q\n", ReverseString(hello))
    student := "i am a student"
    fmt.Printf("%q\n", student)
    fmt.Printf("%q\n", ReverseString(student))
}

https://go.dev/play/p/2ZpYsBQkiiA

"hello world"
"d_l_r_o_w o_l_l_e_h"
"i am a student"
"t_n_e_d_u_t_s a m_a i"
  •  Tags:  
  • go
  • Related