How to get the last word from a string in Go

4 Answers

0 votes
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Go programming language simple to build secure scalable systems"
	
	words := strings.Fields(str)
	if len(words) > 0 {
		lastWord := words[len(words) - 1]
		fmt.Println("Last word:", lastWord)
	} else {
		fmt.Println("No words found.")
	}
}



/*
run:

Last word: systems

*/

 



answered Jan 4, 2025 by avibootz
0 votes
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Go programming language simple to build secure scalable systems"
	
	words := strings.Split(str, " ")
	if len(words) > 0 {
		lastWord := words[len(words) - 1]
		fmt.Println("Last word:", lastWord)
	} else {
		fmt.Println("No words found.")
	}
}



/*
run:

Last word: systems

*/

 



answered Jan 4, 2025 by avibootz
0 votes
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Go programming language simple to build secure scalable systems"
	
	lastSpaceIndex := strings.LastIndex(str, " ")
	if lastSpaceIndex != -1 {
		lastWord := str[lastSpaceIndex + 1:]
		fmt.Println("Last word:", lastWord)
	} else {
		fmt.Println("The string is one word:", str)
	}
}


/*
run:

Last word: systems

*/

 



answered Jan 4, 2025 by avibootz
0 votes
package main

import (
	"fmt"
	"strings"
)

// getLastWord returns the last word in a string.
// Empty or whitespace-only strings return an empty string.
func getLastWord(s string) string {
	// Trim leading/trailing whitespace
	s = strings.TrimSpace(s)

	// If nothing remains, return empty string
	if s == "" {
		return ""
	}

	// Split into fields (handles multiple spaces cleanly)
	parts := strings.Fields(s)

	// Return the last element
	return parts[len(parts)-1]
}

func main() {
	tests := []string{
		"vb.net javascript php c c++ python c#",
		"",
		"c#",
		"c c++ java ",
		"  ",
	}

	for i, t := range tests {
		fmt.Printf("%d. %s\n", i+1, getLastWord(t))
	}
}


/*
run:

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

*/

 



answered Mar 27 by avibootz
...