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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,924 questions

51,857 answers

573 users

How to get the middle words of a string in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"math"
	"strings"
)

func getMiddleWords(s string) string {
	wordsSlice := strings.Fields(s)
	numWords := len(wordsSlice)

	if numWords%2 == 0 {
		middle1 := wordsSlice[int(math.Floor(float64(numWords) / 2)) - 1]
		middle2 := wordsSlice[int(math.Floor(float64(numWords) / 2))]
		
		return middle1 + " " + middle2
	} else {
		middleMinus1 := wordsSlice[int(math.Floor(float64(numWords) / 2)) - 1]
		middle := wordsSlice[int(math.Floor(float64(numWords) / 2))]
		middlePlus1 := wordsSlice[int(math.Floor(float64(numWords) / 2)) + 1]
		
		return middleMinus1 + " " + middle + " " + middlePlus1
	}
}

func main() {
	s := "c++ c java golang c# python rust"

	fmt.Println(getMiddleWords(s))
}


/*
run:

java golang c#

*/

 



answered Oct 8, 2024 by avibootz

Related questions

...