ADVERTISEMENT
ADVERTISEMENT

Golang strings.TrimSpace() Function with Examples

Golang | strings.TrimSpace() Function: Here, we are going to learn about the TrimSpace() function of strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 23, 2021

strings.TrimSpace()

The TrimSpace() function is an inbuilt function of strings package which is used to get a string with all leading and trailing white space removed, as defined by Unicode. It accepts a string and returns white spaces removed string.

Syntax:

func TrimSpace(str string) string

Parameter(s):

  • str : The string in which we have to remove leading and trailing white spaces.

Return Value:

The return type of TrimSpace() function is a string, it returns a string with all leading and trailing white space removed.

Example 1:

// Golang program to demonstrate the
// example of strings.TrimSpace() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimSpace("  Hello, world  "))
	fmt.Println(strings.TrimSpace("  Hello,   world  "))
	fmt.Println(strings.TrimSpace("\nHello, world\n"))
	fmt.Println(strings.TrimSpace("\r\tHello, world\r\t"))
	fmt.Println(strings.TrimSpace("\t \n \tHello, world\t\n"))
	fmt.Println(strings.TrimSpace("   Hello, world!!!"))
}

Output:

Hello, world
Hello,   world
Hello, world
Hello, world
Hello, world
Hello, world!!!

Example 2:

// Golang program to demonstrate the
// example of strings.TrimSpace() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str string
	var result string

	str = "   Hi, there! How are you?  "
	result = strings.TrimSpace(str)
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)

	str = "\n\n\nHi, how are you\n\n\n"
	result = strings.TrimSpace(str)
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)

	str = "\t\rHello, world\t\r"
	result = strings.TrimSpace(str)
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)
}

Output:

Actual string :    Hi, there! How are you?  
Trimmed string: Hi, there! How are you?
Actual string : 


Hi, how are you



Trimmed string: Hi, how are you
Actual string : 	
Hello, world	
Trimmed string: Hello, world

Golang strings Package Functions »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.