How to swap first and last character of string in Golang 1.20

Channel:
Subscribers:
5,740
Published on ● Video Link: https://www.youtube.com/watch?v=Jvbb3fu1a60



Category:
Tutorial
Duration: 1:52
2 views
0


In this video we are going to generate source code for the GoLang Program, How to swap first and last character of string using chatGPT.
After generating we will verify and run the generated code.

IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
In this program I have replaced the angled brackets with > or <. once you copy the source code to editor replace it with greater than or less than symbols respectively.



##############SOURCE CODE#########################

package main

import "fmt"
import "os"
import "bufio"

func main() {
// get input from user
var input string
fmt.Print("Enter a string: ")
//fmt.Scan(&input)

//This will scan full string
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
input = scanner.Text()


// check if string has at least 2 characters
if len(input) < 2 {
fmt.Println("Error: string must have at least 2 characters.")
return
}

// extract first and last characters
first := input[0]
last := input[len(input)-1]

// construct swapped string
swapped := string(last) + input[1:len(input)-1] + string(first)

fmt.Printf("Swapped string: %s\n", swapped)
}


##############END OF SOURCE CODE#########################

Below is the explanation for the program:

This program first prompts the user to enter a string using the bufio.NewScanner function.

Next, it checks if the input string has at least 2 characters. If the string is not long enough, the program prints an error message and exits.

If the string has at least 2 characters, the program extracts the first and last characters using array indexing and the len function.

It then constructs the swapped string by concatenating the last character, the middle characters (from index 1 to the second-to-last index), and the first character using the string function to convert the characters back to a string.

The program prints the swapped string using the fmt.Printf function.


#go #goprogramming #golang #golangtutorial #golanguage







Tags:
how to swap first and last character in string in golang
go program to swap first and last character in string
string handling in go
string manipulation in go
strings in go
go Programming Tutorial
go by example
go Language
go projects
go programming projects
go tutorial
golang tutorial
golang projects
go programming course
learn go
how to run go program
golang videos
golang with chatgpt
coding questions
coding interview questions