Skip to content

proposal: strings: Add new Reverse API #68348

@h3ssan

Description

@h3ssan

Proposal Details

Summary

This proposal suggests adding a new Reverse function to the strings package in the Go standard library. The function will reverse the characters of a given string and handle Unicode characters properly by converting the input string to a slice of runes before reversing.

Motivation

Reversing a string is a common requirement in various applications, including text processing, data manipulation, and algorithm implementation. Currently, we need to implement our own string reversal functions, which can lead to inconsistencies and potential errors, especially when dealing with Unicode characters. Providing a built-in Reverse API in the strings package will offer a standardized and reliable solution for this common task.

API Signature

The Reverse API Signature takes a string and return a new reversed string:

func Reverse(s string) string

Implementation

Here is the full proposed implementation for the API.

// Reverse returnes a copy of s but reversed
func Reverse(s string) string {
	// Convert string to a rune slice
	// to reverse strings containing multi-byte characters accurately
	runes := []rune(s)

	// Reverse the rune slice
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}

	// Return the string representation of the rune slice
	return string(runes)
}

Thank you.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions