将多个空格合并为单个空格;删除尾随/前导空格 [英] Merge Multiple spaces to single space; remove trailing/leading spaces

查看:151
本文介绍了将多个空格合并为单个空格;删除尾随/前导空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多个空格合并为一个空格(空格也可以是制表符)并删除尾随/前导空格.

I want to merge multiple spaces into single space(space could be tab also) and remove trailing/leading spaces.

例如...

string <- "Hi        buddy        what's up    Bro" 

"Hi buddy what's up bro"

我检查了 Regex 中给出的解决方案以替换多个空格一个空格.请注意,不要将 \t 或 \n 作为玩具字符串内的确切空间,并将其作为 gsub 中的模式输入.我想要在 R 中.

I checked the solution given at Regex to replace multiple spaces with a single space. Note that don't put \t or \n as exact space inside the toy string and feed that as pattern in gsub. I want that in R.

请注意,我无法在玩具字符串中放置多个空格.谢谢

Note that I am unable to put multiple space in toy string. Thanks

推荐答案

这似乎可以满足您的需求.

This seems to meet your needs.

string <- "  Hi buddy   what's up   Bro "
library(stringr)
str_replace(gsub("\\s+", " ", str_trim(string)), "B", "b")
# [1] "Hi buddy what's up bro"

这篇关于将多个空格合并为单个空格;删除尾随/前导空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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