From 0fb5475bdf0e5352d7aac67d2ec97c0513ee0af3 Mon Sep 17 00:00:00 2001 From: Dmitry Vyukov Date: Wed, 29 Apr 2015 20:45:55 +0300 Subject: bytes, strings: add LastIndexByte Currently the packages have the following index functions: func Index(s, sep []byte) int func IndexAny(s []byte, chars string) int func IndexByte(s []byte, c byte) int func IndexFunc(s []byte, f func(r rune) bool) int func IndexRune(s []byte, r rune) int func LastIndex(s, sep []byte) int func LastIndexAny(s []byte, chars string) int func LastIndexFunc(s []byte, f func(r rune) bool) int Searching for the last occurrence of a byte is quite common for string parsing algorithms (e.g. find the last paren on a line). Also addition of LastIndexByte makes the set more orthogonal. Change-Id: Ida168849acacf8e78dd70c1354bef9eac5effafe Reviewed-on: https://go-review.googlesource.com/9500 Reviewed-by: Rob Pike --- src/strings/strings.go | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src/strings/strings.go') diff --git a/src/strings/strings.go b/src/strings/strings.go index c6085f51d5..7b8a6b536b 100644 --- a/src/strings/strings.go +++ b/src/strings/strings.go @@ -271,6 +271,16 @@ func LastIndexAny(s, chars string) int { return -1 } +// LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s. +func LastIndexByte(s string, c byte) int { + for i := len(s) - 1; i >= 0; i-- { + if s[i] == c { + return i + } + } + return -1 +} + // Generic split: splits after each instance of sep, // including sepSave bytes of sep in the subarrays. func genSplit(s, sep string, sepSave, n int) []string { -- cgit v1.3-5-g9baa