SoFunction
Updated on 2025-03-05

In-depth analysis of Go string operations

importance

Basic skills of string processing are often used in both interview algorithms and work. Below we explain string processing in the form of an algorithm + a practical work scenario.

The following algorithms are all from leecode China

Invert string

Let's do the original question first344Question invert string

The original title requires no additional space to be reversed in situ.

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

A loop is reversed directly.

func reverseString(s []byte)  {
    //Double pointers, one puts the head and the other puts the tail    i:=0 
    j:=len(s)-1
    //Reverse the elements in these two positions    for i<j {
        s[i],s[j]=s[j],s[i]
        i++
        j--
    }
    
}

in the case ofpythonDirect onerevertThen it came out,GoIt's really troublesome to write by yourself.

Split and merge strings

The question is passed directly into byte array. How to deal with it externally? It's string andbyteround-trip conversion.

s := []byte(str)
reverseString(s)
(string(s))

This will turn the string into bytes, imagine a scene where your article has multiple tags, all stuffed into a field. How to split the display?

# SplitstrList := ("Go language, channel, concurrency", ",")
(strList)
# Mergestr := (strList,",")
(str)
  • stringsIt is a package that encapsulates many string processing functions.
  • Split, parameters one is a string, and parameters two are splitters
  • Merge, parameters one is a string array, and parameters two are splitters used for merge

Ignore case judgments, etc.

A verification code scenario, for example, the verification code is2s5GUser input2s5gIn fact, it is also right.

Just convert all to uppercase, or all to lowercase, etc. I'm a bit rougher, I can't understand and leave a message.

("2s5G") == "2s5g"
("2s5G") == "2S5G"

certainlystringsIt directly provides a method to determine whether it is equal in case insensitive.

(("abc", "ABC"))

Naming a snake to a camel

Involved in knowledge points: splitting, upper case conversion, combination

func main() {
	name := "ab_cde_as"
	strList := (name,"_")
	for index,str := range strList{
		strList[index] = (string(str[0])) + str[1:]
	}
	name = (strList,"")
	(name)
}
  • OutputAbCdeAs
  • str[0]Take one of the characters,str[1:]Slice the string and get[1,len(str)]A string with a closed interval.

You can use it directly now("hello")Come and get itHello

Replace and search

Replacement and search are also relatively high-frequency operations. Commonly used in configuration replacement, but basicallysedThe order is done.

("ip:10.1.1.1", "10.1.1.1", "0.0.0.0", -1)

The last one is the number of times,-1It means all replacements, if only once is replaced1

Under normal circumstances, it is not so stupid. It is all matched using regular methods. For example, I had a requirement before.Take out all the image URLs, save them in my object storage, and insert them back, I wrote a program.

I'll write a simple version. Test whether the regular matches and outputok

regexStr := "https*://[^\\s]*(jpg|png)"
	if ok, _ := (regexStr, "/"); ok {
		("ok")
	}

Start doing it

data := `
![](/)
[](/)
![](/)

`
	re, _ := (regexStr)
	picList := (data,-1)
	(picList)
	for k,v:=range picList{
		if k!=0 && picList[k]==picList[k-1]{
			continue
		}
		//Omit changing the image link		afterStr := "xxx"
		re,_ = (v)
		data = (data,afterStr)
	}
	(data)
  • (regexStr)Load regular expressions.
  • (data,-1)Find all matching results, parameter 2 represents how many to find,-1That's all. Return onelist
  • (data,afterStr)Replace all matches in all original strings, which are the new string (parameter 2), and return the result after replacement.
  • As for why the fourth-last line is loaded again, it is because the current image needs to be used as a regular match to all the contents of this image.
  • As for why you want to sort it, it is to deduplicate it, skip the repeated matching parts.

Other quick checks

Judge size1Formerly big0Same-1Back to big

("a", "b")

Substring contains

(("hello", "he"))

Returns the number of times the substring appears

(("happy", "p")) 

Determine whether a string starts and ends with a substring

(("hello", "he"))
(("hello", "lo"))

Returns the position where the string first appears. No existence returns -1

(("abandon already", "a")) 

Returns the last occurrence of the string. Returns -1

(("abandon already", "a"))

other

Handle Chinese charactersutf8I won't expand on the bag.

The above is the detailed content of in-depth analysis of Go string operations. For more information about Go string operations, please pay attention to my other related articles!