在Go中提取子字符串 [英] Extracting substrings in Go

查看:385
本文介绍了在Go中提取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从控制台读取整行(包括空格),然后处理它。使用bufio.ReadString,换行符与输入一起读取,所以我想出了以下代码来修剪换行符:

  input,_:= src.ReadString('\\\
')
inputFmt:= input [0:len(input)-2] +//需要手动添加字符串

是否有更习惯的方式来做到这一点?也就是说,是否已经有一个库在为你提取子字符串时负责结束空字节?



(是的,我知道已经有一种方法可以读取在去掉readline - >字符串中没有换行符的行,但我正在寻找更多优雅的字符串操作。)

解决方案

看起来你对片的工作和字符串存储格式感到困惑,你有C语言。


  • Go中的任何切片都会存储长度(以字节为单位),因此您不必关心成本 len 操作:无需计数

  • Go字符串不是空的,因此您不必删除空字节,并且您不必在添加一个空字符串之后添加 1



删除最后一个字符(如果它是一个字节的字符),si mply do

  inputFmt:= input [0:len(input)-1] 

正如Uriel所注意到的,您可以缩短为

  inputFmt:= input [:len(input)-1] 


I'm trying to read an entire line from the console (including whitespace), then process it. Using bufio.ReadString, the newline character is read together with the input, so I came up with the following code to trim the newline character:

input,_:=src.ReadString('\n')
inputFmt:=input[0:len(input)-2]+"" //Need to manually add end of string

Is there a more idiomatic way to do this? That is, is there already a library that takes care of the ending null byte when extracting substrings for you?

(Yes, I know there is already a way to read a line without the newline character in go readline -> string but I'm looking more for elegant string manipulation.)

解决方案

It looks like you're confused by the working of slices and the string storage format, which is different from what you have in C.

  • any slice in Go stores the length (in bytes), so you don't have to care about the cost of the len operation : there is no need to count
  • Go strings aren't null terminated, so you don't have to remove a null byte, and you don't have to add 1 after slicing by adding an empty string.

To remove the last char (if it's a one byte char), simply do

inputFmt:=input[0:len(input)-1]

And as noticed by Uriel, you can shorten that as

inputFmt:=input[:len(input)-1]

这篇关于在Go中提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆