How to find the largest and the smallest word in a string with Go

1 Answer

0 votes
package main

import (
	"fmt"
	"strings"
)

func findLargestAndSmallestWords(s string) (string, string) {
	words := strings.Fields(s)
	if len(words) == 0 {
		return "", ""
	}

	largest, smallest := words[0], words[0]

	for _, word := range words {
		if len(word) > len(largest) {
			largest = word
		}
		if len(word) < len(smallest) {
			smallest = word
		}
	}

	return largest, smallest
}

func main() {
	s := "Go is statically typed, compiled general purpose programming language"
	
	largest, smallest := findLargestAndSmallestWords(s)
	
	fmt.Printf("Largest word: %s\n", largest)
	fmt.Printf("Smallest word: %s\n", smallest)
}

 
 
 
/*
run:

Largest word: programming
Smallest word: Go
 
*/

 



answered Dec 27, 2024 by avibootz

Related questions

1 answer 123 views
1 answer 135 views
1 answer 130 views
1 answer 109 views
1 answer 103 views
...