简体   繁体   English

给定长度不同的字符串数组,如何用相同的单词替换每个字符串

[英]Given an array of strings varying in length, how can I replace every string with the same word

I have to replace a number of strings with the same word, lets say that word is "plum".我必须用同一个词替换一些字符串,假设这个词是“plum”。

An example could be... "This is a string" and expected output would be "plum plum plum plum" or "I'm happy" output "plum plum"一个例子可能是......“这是一个字符串”,预期输出将是“李子李子李子”或“我很高兴”输出“李子李子”

So far I have converted the string into an array, mapped and counted using...到目前为止,我已将字符串转换为数组,并使用...

string = sentence.split(&:map).to_a
n = string.count.to_i

I am now trying to replace each string in the array using sentence.gsub[0..n] which I expected to replace each position in the array with my word.我现在正在尝试使用sentence.gsub[0..n]替换数组中的每个字符串,我希望用我的单词替换数组中的每个位置。

I'm sure this is not the best way to do this, however I would really appreciate help on this particular method to help my understanding of where I've gone wrong in my thinking as well as finding out that I could have done it with far cleaner code我敢肯定这不是最好的方法,但是我真的很感激这个特定方法的帮助,以帮助我理解我的想法哪里出错了,并发现我可以做到这一点更干净的代码

You can try this way:你可以试试这个方法:

"This is a string".split.map { "plum" }.join(" ")
=> "plum plum plum plum"

Or by using gsub :或者通过使用gsub

"This is a string".gsub(/[^\s]+/, "plum")
=> "plum plum plum plum"

You can just repeat "plum" as many times as you have words...您可以根据单词重复“梅花”多少次...

sentence = "This is a string"
("plum " * sentence.split.count).strip
=> "plum plum plum plum"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript Array String Word Wrap Problem ---按顺序排列字符串和给定数组长度 - Javascript Array String Word Wrap Problem --- Permutation of Strings in Order and A Given Array Length ruby-如何生成给定长度的字母和数字的每种组合的数组? - ruby - How can I generate an array of every combination of letters and numbers of a given length? 为什么无法获取数组中每个字符串的数组长度? - Why can't I get the array length of every string in the array? 如何从始终具有相同长度的字符串中获取最大字节数组长度? - How can I get the maximum byte array length from a string that has always the same length? 如何检查输入字符串是否部分匹配 php 中给定数组中的任何单词? - How can I check whether the input string partailly matches any word in the given array in php? 如何用数组中的 2 个字符串替换 1 个字符串? - How to replace 1 string with 2 strings in an array? 如何在js中拆分不同长度的字符串? - How to split strings in js with varying length? 如何创建给定长度和相同数字的数组? - How to create array of given length and same number? 如何在C中浏览任意长度的字符串数组? - How can I navigate through an array of strings of any length in C? 我怎样才能将字符串中每个单词的第一个字母大写? - How can I uppercase the first letter of every word in a string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM