在PHP中,字符串的赋值虽然只有一行,其实包含了两步,一是声明变量,二是赋值给变量,同一个变量可以任意重新赋值。

  1. $str = 'Hello World!';
  2. $str = 'hia';

Go语言实现上述两步也可以用一行语句解决,就是通过标识var赋值时同时声明变量,切记等号右侧的字符串不能用单引号,对变量的后续赋值也不能再重新声明,否则会报错。除此之外,定义的变量不使用也会报错,从这点来看,Go还是比PHP严格很多的,规避了很多在开发阶段产生的性能问题。

  1. var str = "Hello World!"
  2. str = "hia"

关于声明,Go提供了一种简化方式,不需要在行首写var,只需将等号左侧加上一个冒号就好了,切记这只是替代了声明语句,它并不会像PHP那样用一个赋值符号来统一所有的赋值操作。

  1. str := "Hello World!"
  2. str = "hia"

PHP中的输出非常简单,一个echo就搞定了。

  1. <?php
  2. echo 'Hello World!';
  3. ?>

而Go不一样的是,调用它的输出函数前需要先引入包fmt,这个包提供了非常全面的输入输出函数,如果只是输出普通字符串,那么和PHP对标的函数就是Print了,从这点来看,Go更有一种万物皆对象的感觉。

  1. import "fmt"
  2. func main() {
  3. fmt.Print("Hello world!")
  4. }

在PHP中还有一个格式化输出函数sprintf,可以用占位符替换字符串。

  1. echo sprintf('name:%s', '平也'); //name:平也

在Go中也有同名同功能的字符串格式化函数。

  1. fmt.Print(fmt.Sprintf("name:%s", "平也"))

官方提供的默认占位符有以下几种,感兴趣的同学可以自行了解。

  1. bool: %t
  2. int, int8 etc.: %d
  3. uint, uint8 etc.: %d, %#x if printed with %#v
  4. float32, complex64, etc: %g
  5. string: %s
  6. chan: %p
  7. pointer: %p

在PHP中通过strlen计算字符串长度。

  1. echo strlen('平也'); //output: 6

在Go中也有类似函数len

  1. fmt.Print(len("平也")) //output: 6

因为统计的是ASCII字符个数或字节长度,所以两个汉字被认定为长度6,如果要统计汉字的数量,可以使用如下方法,但要先引入unicode/utf8包。

  1. import (
  2. "fmt"
  3. "unicode/utf8"
  4. )
  5. func main() {
  6. fmt.Print(utf8.RuneCountInString("平也")) //output: 2
  7. }

PHP有一个substr函数用来截取任意一段字符串。

  1. echo substr('hello,world', 0, 3); //output: hel

Go中的写法有些特别,它是将字符串当做数组,截取其中的某段字符,比较麻烦的是,在PHP中可以将第二个参数设置为负数进行反向取值,但是Go无法做到。

  1. str := "hello,world"
  2. fmt.Print(str[0:3]) //output: hel

PHP中使用strpos查询某个字符串出现的位置。

  1. echo strpos('hello,world', 'l'); //output: 2

Go中需要先引入strings包,再调用Index函数来实现。

  1. fmt.Print(strings.Index("hello,world", "l")) //output: 2

PHP中替换字符串使用str_replace内置函数。

  1. echo str_replace('world', 'girl', 'hello,world'); //output: hello,girl

Go中依然需要使用strings包中的函数Replace,不同的是,第四个参数是必填的,它代表替换的次数,可以为0,代表不替换,但没什么意义。还有就是字符串在PHP中放在第三个参数,在Go中是第一个参数。

  1. fmt.Print(strings.Replace("hello,world", "world", "girl", 1)) //output: hello,girl

在PHP中最经典的就是用点来连接字符串。

  1. echo 'hello' . ',' . 'world'; //output: hello,world

在Go中用加号来连接字符串。

  1. fmt.Print("hello" + "," + "world") //output: hello,world

除此之外,还可以使用strings包中的Join函数连接,这种写法非常类似与PHP中的数组拼接字符串函数implode

  1. str := []string{"hello", "world"}
  2. fmt.Print(strings.Join(str, ",")) //output: hello,world

PHP中使用内置函数base64_encode来进行编码。

  1. echo base64_encode('hello, world'); //output: aGVsbG8sIHdvcmxk

在Go中要先引入encoding/base64包,并定义一个切片,再通过StdEncoding.EncodeToString函数对切片编码,比PHP要复杂一些。

  1. import (
  2. "encoding/base64"
  3. "fmt"
  4. )
  5. func main() {
  6. str := []byte("hello, world")
  7. fmt.Print(base64.StdEncoding.EncodeToString(str))
  8. }

以上是PHP与Go在常用的字符串处理场景中的区别,感兴趣的同学可以自行了解。

版权声明:本文为enochzzg原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/enochzzg/p/11000425.html