【问题标题】:Insert "and" before last element in string在字符串的最后一个元素之前插入“and”
【发布时间】:2015-08-07 09:17:37
【问题描述】:

假设我有这个字符串:

fruits <- c("apple", "pear", "orange", "banana", "melon")

我可以像这样将每个元素折叠成一个字符串:

cat(paste(fruits, collapse = ", "))

但是如何在最后一个元素之前插入 and 呢?请注意,我的真实字符串的长度各不相同。

输出应该是:

apple, pear, orange, banana and melon

【问题讨论】:

  • 只需执行c(fruits[-length(fruits)], 'and') 并粘贴fruits[length(fruits)]

标签: r string text


【解决方案1】:

你可以使用子

> cat(sub("(.*),", "\\1 and",paste(fruits, collapse = ", ")))
apple, pear, orange, banana and melon

【讨论】:

    猜你喜欢
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多