有没有用于截断字符串的Go函数?

huangapple go评论73阅读模式
英文:

Is there an Go function for truncating string?

问题

请帮我编写一个函数,该函数接受一个字符串和一个数字作为输入,并输出一个缩短的字符串,长度为数字加上"..."。如果字符串不超过给定的长度(数字),则只输出该字符串,不包含"..."。另外,我们的字符串只使用单字节字符,并且数字严格大于零。

我的两个尝试:

package main

import (
    "fmt"
)

func main() {
    var text string
    var width int
    fmt.Scanf("%s %d", &text, &width)
    res := text[:width]
    fmt.Println(res + "...")
}

但是这个函数即使字符串没有超过给定的宽度,也会添加"..."。

package main

import (
    "fmt"
)

var text string
var width int

func main() {
    fmt.Scanf("%s %d", &text, &width)
    if width <= 0 {
        fmt.Println("")
    }
    res := ""
    count := 0
    for _, char := range text {
        res += string(char)
        count++
        if count >= width {
            break
        }
    }
    fmt.Println(res + "...")
}

这个函数的工作方式相同。

英文:

Please help me write a function that takes input of a string and a number and outputs a shortened string to the number + "...". If the string does not exceed the size (number), then just output this string, but without the "...". Also, our string uses only single-byte characters and the number is strictly greater than zero.

My two attempts:

package main

import (
        &quot;fmt&quot;
)
func main() {
var text string
var width int
fmt.Scanf(&quot;%s %d&quot;,&amp;text,&amp;width)
res := text[:width]
fmt.Println(res+&quot;...&quot;)
}

But this function adds "..." even if the string does not exceed the width.

package main
import (
        &quot;fmt&quot;
)
var text string
var width int
fmt.Scanf(&quot;%s %d&quot;,&amp;text,&amp;width)
if width &lt;= 0 {
    fmt.Println(&quot;&quot;)
}
res := &quot;&quot;
count := 0
for _, char := range text {
res += string(char)
    count++
    if count &gt;= width {
        break
    }
}
fmt.Println(res+&quot;...&quot;)
}

This function works the same way.

答案1

得分: 1

继续@Marcelloh所说的内容,这是一个使用符文而不是字节的示例。

package main

import (
	"fmt"
)

func Truncate(text string, width int) (string, error) {
	if width < 0 {
		return "", fmt.Errorf("无效的宽度大小")
	}

	r := []rune(text)
	trunc := r[:width]
	return string(trunc) + "...", nil
}

func main() {
	word, err := Truncate("Hello, World", 3)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(word)
	// 输出: Hel...
}
英文:

To continue with what @Marcelloh said

Here's an example of using runes instead of bytes.

package main

import (
	&quot;fmt&quot;
)

func Truncate(text string, width int) (string, error) {
	if width &lt; 0 {
		return &quot;&quot;, fmt.Errorf(&quot;invalid width size&quot;)
	}
	
	r := []rune(text)
	trunc := r[:width]
	return string(trunc)+ &quot;...&quot;, nil
}

func main() {
	word, err := Truncate(&quot;Hello, World&quot;, 3)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(word)
    // Output: Hel...
}

答案2

得分: 0

以下是翻译好的内容:

只是一个可以让你开始的基本示例 有没有用于截断字符串的Go函数?

func main() {
	var text string
	var width int = 12
	text = "一个非常长的字符串,需要缩短"
	if len(text) > width {
		text = string([]byte(text)[:width])
	}
	fmt.Println(text + "...")
}

当然,你需要了解一些关于符文(runes)的知识,有些 "字符串" 的长度为3,而你只看到一个字符。但对于普通的ASCII字符,上述代码就可以起作用。

英文:

Just a basic example that can get you going 有没有用于截断字符串的Go函数?

func main() {
	var text string
	var width int = 12
	text = &quot;a ver long string of text to be shortened&quot;
	if len(text) &gt; width {
		text = string([]byte(text)[:width])

	}
	fmt.Println(text + &quot;...&quot;)
}

Of course, you need to read about runes, and some "strings" have a length of 3, while you see only one. But for normal ASCII, the above would do the trick.

答案3

得分: -1

package main

import (
    "fmt"
)

func main() {
    var text string
    var width int
    fmt.Scanf("%s %d", &text, &width)
    res := []rune(text)
    if len(res) > width {
        res = res[:width]
        fmt.Println(string(res) + "...")
    } else {
        fmt.Println(string(res))
    }
}
package main

import (
    "fmt"
)

func main() {
    var text string
    var width int
    fmt.Scanf("%s %d", &text, &width)
    res := []rune(text)
    if len(res) > width {
        res = res[:width]
        fmt.Println(string(res) + "...")
    } else {
        fmt.Println(string(res))
    }
}
英文:
package main

import (
    &quot;fmt&quot;
)

func main(){
    var text string
    var width int
    fmt.Scanf(&quot;%s %d&quot;,&amp;text,&amp;width)
    res := []rune(text)
    if len(res) &gt; width {
        res = res[:width]
        fmt.Println(string(res)+&quot;...&quot;)
    } else {
        fmt.Println(string(res))
    }
}

huangapple
  • 本文由 发表于 2021年10月11日 22:34:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/69527988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定