- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Replace characters in a Golang string?
The strings package of Golang has a Replace() function which we can use to replace some characters in a string with a new value. It replaces only a specified "n" occurrences of the substring.
In addition to Replace(), there is a ReplaceAll() function that replaces all the occurrences of a given substring with a new value.
Syntax
func Replace(s, old, new string, n int) string
Where,
s is the given string
old is the string which we want to replace
new is the string which will replace the old string
n represents the number of characters which we want to replace in the given string.
Example
The following example demonstrates how you can use the Replace() function to replace a substring with a new string.
package main import ( "fmt" "strings" ) func main() { // Initializing the Strings s := "Go Programming Language" old := "Go" newstring := "Golang" n := 1 // Display the Strings fmt.Println("Original String: ", s) // Using the Replace Function testresult := strings.Replace(s, old, newstring, n) // Display the Replace Output fmt.Println("Replace Go with Golang:", testresult) }
Output
It will generate the following output −
Original String: Go Programming Language Replace Go with Golang: Golang Programming Language
Example
In this example, we are going to see how to replace a single character with a new value at a particular defined postion or index.
package main import ( "fmt" "strings" ) func main() { // Initializing the Strings x := "Replace String Function" y := "Go Language" // Display the Strings fmt.Println("1st String:", x) fmt.Println("2nd String:", y) // Using the Replace Function test1 := strings.Replace(x, "i", "I", 2) test2 := strings.Replace(y, "g", "G", -1) // Display the Replace Output fmt.Println("\n Replace 'i' with 'I' in the 1st String: \n", test1) fmt.Println("\n Replace 'g' with 'G' in the 2nd String: \n", test2) }
Output
It will generate the following output −
1st String: Replace String Function 2nd String: Go Language Replace 'i' with 'I' in the 1st String: Replace StrIng FunctIon Replace 'g' with 'G' in the 2nd String: Go LanGuaGe