PHP转Go系列字符串

32次阅读

共计 2334 个字符,预计需要花费 6 分钟才能阅读完成。

字符串的赋值

在 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 在常用的字符串处理场景中的区别,感兴趣的同学可以自行了解。

正文完
 0