PHP转Go系列之字符串

字符串的赋值

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

$str = 'Hello World!';
$str = 'hia';
复制代码

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

var str = "Hello World!"
str = "hia"
复制代码

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

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,能够用占位符替换字符串。ui

echo sprintf('name:%s', '平也');  //name:平也
复制代码

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

fmt.Print(fmt.Sprintf("name:%s", "平也"))
复制代码

官方提供的默认占位符有如下几种,感兴趣的同窗能够自行了解。spa

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计算字符串长度。code

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

相关文章
相关标签/搜索