
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Golang Program to Reverse a String
Examples
- Input str = “himalaya” => Reverse String would be like => “ayalamih”
- Input str = “mountain” => Reverse String would be like => “niatnuom”
Approach to solve this problem
- Step 1: Define a function that accepts a string, i.e., str.
- Step 2: Convert str to byte string.
- Step 3: Start iterating the byte string.
- Step 4: Swap the first element with the last element of converted byte string.
- Step 5: Convert the byte string to string and return it.
Program
package main import "fmt" func reverseString(str string) string{ byte_str := []rune(str) for i, j := 0, len(byte_str)-1; i < j; i, j = i+1, j-1 { byte_str[i], byte_str[j] = byte_str[j], byte_str[i] } return string(byte_str) } func main(){ fmt.Println(reverseString("himalaya")) fmt.Println(reverseString("taj")) fmt.Println(reverseString("tropical")) }
Output
ayalamih jat laciport
Advertisements