Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

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