在PHP中,字符串的賦值雖然只有一行,其實包含了兩步,一是聲明變量,二是賦值給變量,同一個變量能夠任意從新賦值。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更有一種萬物皆對象的感受。ui
import "fmt" func main() { fmt.Print("Hello world!") }
在PHP中還有一個格式化輸出函數sprintf
,能夠用佔位符替換字符串。編碼
echo sprintf('name:%s', '平也'); //name:平也
在Go中也有同名同功能的字符串格式化函數。code
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
計算字符串長度。unicode
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在經常使用的字符串處理場景中的區別,感興趣的同窗能夠自行了解。