字符串的賦值
在PHP中,字符串的賦值雖然只有一行,其實包含了兩步,一是聲明變量,二是賦值給變量,同一個變量可以任意重新賦值。
$str = 'Hello World!';
$str = 'hia';
Go語言實現上述兩步也可以用一行語句解決,就是通過標識var
賦值時同時聲明變量,切記等號右側的字符串不能用單引號,對變量的后續賦值也不能再重新聲明,否則會報錯。除此之外,定義的變量不使用也會報錯,從這點來看,Go還是比PHP嚴格很多的,規避了很多在開發階段產生的性能問題。
var str = "Hello World!"
str = "hia"
關於聲明,Go提供了一種簡化方式,不需要在行首寫var,只需將等號左側加上一個冒號就好了,切記這只是替代了聲明語句,它並不會像PHP那樣用一個賦值符號來統一所有的賦值操作。
str := "Hello World!"
str = "hia"
字符串的輸出
PHP中的輸出非常簡單,一個echo就搞定了。
<?php
echo 'Hello World!';
?>
而Go不一樣的是,調用它的輸出函數前需要先引入包fmt
,這個包提供了非常全面的輸入輸出函數,如果只是輸出普通字符串,那么和PHP對標的函數就是Print
了,從這點來看,Go更有一種萬物皆對象的感覺。
import "fmt"
func main() {
fmt.Print("Hello world!")
}
在PHP中還有一個格式化輸出函數sprintf
,可以用占位符替換字符串。
echo sprintf('name:%s', '平也'); //name:平也
在Go中也有同名同功能的字符串格式化函數。
fmt.Print(fmt.Sprintf("name:%s", "平也"))
官方提供的默認占位符有以下幾種,感興趣的同學可以自行了解。
bool: %t
int, int8 etc.: %d
uint, uint8 etc.: %d, %#x if printed with %#v
float32, complex64, etc: %g
string: %s
chan: %p
pointer: %p
字符串的相關操作
字符串長度
在PHP中通過strlen
計算字符串長度。
echo strlen('平也'); //output: 6
在Go中也有類似函數len
。
fmt.Print(len("平也")) //output: 6
因為統計的是ASCII字符個數或字節長度,所以兩個漢字被認定為長度6,如果要統計漢字的數量,可以使用如下方法,但要先引入unicode/utf8
包。
import (
"fmt"
"unicode/utf8"
)
func main() {
fmt.Print(utf8.RuneCountInString("平也")) //output: 2
}
字符串截取
PHP有一個substr
函數用來截取任意一段字符串。
echo substr('hello,world', 0, 3); //output: hel
Go中的寫法有些特別,它是將字符串當做數組,截取其中的某段字符,比較麻煩的是,在PHP中可以將第二個參數設置為負數進行反向取值,但是Go無法做到。
str := "hello,world"
fmt.Print(str[0:3]) //output: hel
字符串搜索
PHP中使用strpos
查詢某個字符串出現的位置。
echo strpos('hello,world', 'l'); //output: 2
Go中需要先引入strings
包,再調用Index
函數來實現。
fmt.Print(strings.Index("hello,world", "l")) //output: 2
字符串替換
PHP中替換字符串使用str_replace
內置函數。
echo str_replace('world', 'girl', 'hello,world'); //output: hello,girl
Go中依然需要使用strings
包中的函數Replace
,不同的是,第四個參數是必填的,它代表替換的次數,可以為0,代表不替換,但沒什么意義。還有就是字符串在PHP中放在第三個參數,在Go中是第一個參數。
fmt.Print(strings.Replace("hello,world", "world", "girl", 1)) //output: hello,girl
字符串連接
在PHP中最經典的就是用點來連接字符串。
echo 'hello' . ',' . 'world'; //output: hello,world
在Go中用加號來連接字符串。
fmt.Print("hello" + "," + "world") //output: hello,world
除此之外,還可以使用strings
包中的Join
函數連接,這種寫法非常類似與PHP中的數組拼接字符串函數implode
。
str := []string{"hello", "world"}
fmt.Print(strings.Join(str, ",")) //output: hello,world
字符串編碼
PHP中使用內置函數base64_encode
來進行編碼。
echo base64_encode('hello, world'); //output: aGVsbG8sIHdvcmxk
在Go中要先引入encoding/base64
包,並定義一個切片,再通過StdEncoding.EncodeToString
函數對切片編碼,比PHP要復雜一些。
import (
"encoding/base64"
"fmt"
)
func main() {
str := []byte("hello, world")
fmt.Print(base64.StdEncoding.EncodeToString(str))
}
以上是PHP與Go在常用的字符串處理場景中的區別,感興趣的同學可以自行了解。