Skip to main content
ubuntuask.com

Back to all posts

How to Iterate Through A String In Golang?

Published on
5 min read
How to Iterate Through A String In Golang? image

Best Books on Go Programming to Buy in October 2025

1 Learning Go: An Idiomatic Approach to Real-World Go Programming

Learning Go: An Idiomatic Approach to Real-World Go Programming

BUY & SAVE
$45.95 $65.99
Save 30%
Learning Go: An Idiomatic Approach to Real-World Go Programming
2 Go Programming Language, The (Addison-Wesley Professional Computing Series)

Go Programming Language, The (Addison-Wesley Professional Computing Series)

BUY & SAVE
$28.29 $49.99
Save 43%
Go Programming Language, The (Addison-Wesley Professional Computing Series)
3 100 Go Mistakes and How to Avoid Them

100 Go Mistakes and How to Avoid Them

BUY & SAVE
$39.16 $69.99
Save 44%
100 Go Mistakes and How to Avoid Them
4 Mastering Go: Leverage Go's expertise for advanced utilities, empowering you to develop professional software

Mastering Go: Leverage Go's expertise for advanced utilities, empowering you to develop professional software

BUY & SAVE
$27.22 $54.99
Save 51%
Mastering Go: Leverage Go's expertise for advanced utilities, empowering you to develop professional software
5 Network Programming with Go: Code Secure and Reliable Network Services from Scratch

Network Programming with Go: Code Secure and Reliable Network Services from Scratch

BUY & SAVE
$34.57 $49.99
Save 31%
Network Programming with Go: Code Secure and Reliable Network Services from Scratch
6 GO Programming in easy steps: Learn coding with Google's Go language

GO Programming in easy steps: Learn coding with Google's Go language

BUY & SAVE
$13.39 $15.99
Save 16%
GO Programming in easy steps: Learn coding with Google's Go language
7 Black Hat Go: Go Programming For Hackers and Pentesters

Black Hat Go: Go Programming For Hackers and Pentesters

  • MASTER GO FOR HACKING & PENTESTING WITH EXPERT INSIGHTS.
  • HANDS-ON TECHNIQUES FOR REAL-WORLD SECURITY CHALLENGES.
  • ACCESSIBLE PAPERBACK FORMAT FOR EASY REFERENCE AND STUDY.
BUY & SAVE
$31.65 $44.99
Save 30%
Black Hat Go: Go Programming For Hackers and Pentesters
8 Microservices with Go: The expert's guide to building secure, scalable, and reliable microservices with Go

Microservices with Go: The expert's guide to building secure, scalable, and reliable microservices with Go

BUY & SAVE
$35.99 $44.99
Save 20%
Microservices with Go: The expert's guide to building secure, scalable, and reliable microservices with Go
9 System Programming Essentials with Go: System calls, networking, efficiency, and security practices with practical projects in Golang

System Programming Essentials with Go: System calls, networking, efficiency, and security practices with practical projects in Golang

BUY & SAVE
$27.36 $41.99
Save 35%
System Programming Essentials with Go: System calls, networking, efficiency, and security practices with practical projects in Golang
+
ONE MORE?

In Golang, iterating through a string involves accessing each character of the string one by one. Here's how you can do it:

  1. To start, you need to import the strings package.

import ( "strings" )

  1. Create a variable of type string and assign the string you want to iterate through.

str := "Hello, World!"

  1. Use the len() function to find the length of the string.

strLength := len(str)

  1. Iterate through the string by using a for loop and the strings.Split() function to separate each character.

for i := 0; i < strLength; i++ { char := strings.Split(str, "")[i] // Perform any operations you want with the character fmt.Println(char) }

  1. Within the loop, you can perform any operations or actions on each character as required.

Note: It's important to split the string into individual characters using strings.Split() since Go treats strings as read-only character arrays.

By following these steps, you can iterate through a string in Golang and access each character individually.

How to perform a loop over characters in a string using Golang?

In Go, you can perform a loop over characters in a string using a for loop and range keyword. Here's an example:

package main

import "fmt"

func main() { str := "Hello, World!"

for \_, char := range str {
    fmt.Printf("%c\\n", char)
}

}

In this example, we define a string str as "Hello, World!". We use the range keyword to iterate over the characters in the string. The range keyword returns two values on each iteration - the index of the character, and the character itself. Since we are not interested in the index, we use the _ blank identifier to discard it. The character is stored in the char variable.

Inside the loop block, you can perform any operations you want on the character. In this example, we simply print each character using %c format specifier, which represents a Unicode character, followed by a newline character.

When you run this program, it will output each character of the string on a new line:

H e l l o ,

W o r l d !

How to iterate through a string and extract numbers in Golang?

In Golang, you can iterate through a string and extract numbers by using the range keyword to iterate over each character of the string and then using the strconv package to convert the extracted digits into numbers. Here is an example:

package main

import ( "fmt" "strconv" )

func extractNumbersFromString(s string) []int { var numbers []int

for \_, c := range s {
	// Check if the current character is a digit
	if c >= '0' && c <= '9' {
		// Convert the digit character to an integer and append it to the numbers slice
		num, \_ := strconv.Atoi(string(c))
		numbers = append(numbers, num)
	}
}

return numbers

}

func main() { str := "abc123def456ghi789"

numbers := extractNumbersFromString(str)
fmt.Println(numbers) // Output: \[1 2 3 4 5 6 7 8 9\]

}

In the above code, the extractNumbersFromString function iterates over each character c of the input string s. It checks if c is a digit using the condition c >= '0' && c <= '9'. If it is a digit, it converts c into an integer using strconv.Atoi and appends it to the numbers slice.

In the main function, we call extractNumbersFromString with a sample string and print the extracted numbers.

How to iterate through a string and count the occurrences of a specific character in Golang?

To iterate through a string and count the occurrences of a specific character in Golang, you can use the range keyword to loop through each character in the string and compare it to the specific character you are looking for. Here is an example code snippet that demonstrates this:

package main

import "fmt"

func main() { str := "hello world" charToCount := 'o' count := 0

for \_, ch := range str {
    if ch == charToCount {
        count++
    }
}

fmt.Printf("The character '%c' occurs %d times in the string '%s'\\n", charToCount, count, str)

}

In this code, we define a string str, the character to count charToCount, and an initial count value of 0. Then, using the range keyword, we iterate through each character ch in the string. Inside the loop, we check if the character is equal to the character we are looking for, and if so, we increment the count. Finally, we print the result showing the specific character, count, and the original string.

What is a string iteration?

A string iteration refers to the act of traversing or looping through each character of a string, one character at a time. It allows you to access and perform operations on individual characters within the string. String iterations are commonly used in programming languages to manipulate or analyze the contents of a string.

How to iterate through a string in Golang?

To iterate through a string in Golang, you can use a for loop and convert the string to a rune array using the []rune function. Here's an example:

package main

import "fmt"

func main() { str := "Hello, World!" runes := []rune(str)

for i := 0; i < len(runes); i++ {
    fmt.Printf("%c ", runes\[i\])
}

}

In this example, we convert the string str to a rune array using []rune(str). Then, we use a for loop to iterate through the rune array. Inside the loop, we access each rune using runes[i] and print it using %c format specifier in fmt.Printf to display the character.

Output:

H e l l o , W o r l d !