How to make the first letter of a string uppercase in Go Language?

How to make the first letter of a string uppercase, but not change the case of any of the other letters?

For Example:

"go language is awesome" → "Go language is awesome"
"hello world" → "Hello world"


Solution 1: Easy

package main

import (
"unicode"
)

// Main function
func main() {

str := "go language is awesome"
runes := []rune(str)
if len(runes) > 0 {
runes[0] = unicode.ToUpper(runes[0])
}
println(string(runes))
}

Output:



Solution 2: Easy

package main

import "strings"

// Main function
func main() {

str := "go language is awesome"
str = strings.ToUpper(string(str[0])) + str[1:]
println(str)
}

Output:




Solution 3: Normal

package main

import (
"unicode"
"unicode/utf8"
)

// Main function
func main() {

str := "go language is awesome"
println(firstToUpper(str))
}

func firstToUpper(s string) string {
if len(s) > 0 {
r, size := utf8.DecodeRuneInString(s)
if r != utf8.RuneError || size > 1 {
up := unicode.ToUpper(r)
if up != r {
s = string(up) + s[size:]
}
}
}
return s
}

Output:



Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

ReactJS - Bootstrap - Buttons

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

Java, Spring Boot Mini Project - Library Management System - Download

Top 5 Java ORM tools - 2024

Java - DES Encryption and Decryption example