How to remove the last word from a string with Go

2 Answers

0 votes
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "go java c c++ go python go"

	lastSpaceIndex := strings.LastIndex(s, " ")
	if lastSpaceIndex != -1 {
		s = s[:lastSpaceIndex]
	}

	fmt.Println(s)
}

/*

run:

go java c c++ go python

*/

 



answered Sep 6, 2024 by avibootz
0 votes
package main

import (
    "fmt"
    "strings"
)

func removeLastWord(s string) string {
    // Trim trailing spaces
    s = strings.TrimRight(s, " ")

    // Find last space
    pos := strings.LastIndex(s, " ")

    // If no space found, return original
    if pos == -1 {
        return s
    }

    return s[:pos]
}

func main() {
    var s string

    s = "c c++ c# java python"
    fmt.Println("1.", removeLastWord(s))

    s = ""
    fmt.Println("2.", removeLastWord(s))

    s = "c"
    fmt.Println("3.", removeLastWord(s))

    s = "c# java python "
    fmt.Println("4.", removeLastWord(s))

    s = "  "
    fmt.Println("5.", removeLastWord(s))
}


/*
run:

1. c c++ c# java
2. 
3. c
4. c# java
5. 

*/

 



answered Mar 27 by avibootz
...