gpt4 book ai didi

ruby-on-rails - 用 Rails 截断字符串?

转载 作者:数据小太阳 更新时间:2023-10-29 06:20:47 26 4
gpt4 key购买 nike

我想截断一个字符串,如下所示:

输入:

string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa dddddddddddddd"

输出:

string = "abcd asfsa sadfsaf safsdaf aa...ddddd"

最佳答案

看看String#truncate from String#truncate_words来自 Rails,它部分地确实想要你想要的。如果您测试它是否被截断,您可以在截断部分之后添加一些最后一部分。

'Once upon a time in a world far far away'.truncate(27)
# => "Once upon a time in a wo..."

# Pass a string to truncate text at a natural break:
'Once upon a time in a world far far away'.truncate(27, separator: ' ')
# => "Once upon a time in a..."

# The last characters will be replaced with the :omission string (defaults to “…”) for a total length not exceeding length:
'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
# => "And they f... (continued)"
# Truncates a given text after a given number of words (words_count):
'Once upon a time in a world far far away'.truncate_words(4)
# => "Once upon a time..."

# Pass a string to specify a different separator of words:
'Once<br>upon<br>a<br>time<br>in<br>a<br>world'.truncate_words(5, separator: '<br>')
# => "Once<br>upon<br>a<br>time<br>in..."

# The last characters will be replaced with the :omission string (defaults to “…”):
'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
# => "And they found that many... (continued)"

关于ruby-on-rails - 用 Rails 截断字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7023545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com