Ruby如何将字符串按每两个连续相邻单词分割为数组?
实现方法
核心逻辑分为两步:
- 先把原字符串按空白字符分割,得到单个单词组成的数组,分割时建议匹配连续空白字符,兼容单词间存在多个空格、制表符的场景
- 从索引0开始遍历单词数组,直到索引为数组长度-2的位置停止,每次取当前索引和下一个索引的单词用空格拼接,存入结果数组即可
- 边界情况:如果原字符串单词总数小于2,直接返回空数组
常用语言代码示例
Python
def get_word_pairs(input_str): words = input_str.split() return [f"{words[i]} {words[i+1]}" for i in range(len(words)-1)] if len(words) >=2 else [] # 测试用例 test_str = "how are you to day" print(get_word_pairs(test_str)) # 输出:['how are', 'are you', 'you to', 'to day']
JavaScript
function getWordPairs(inputStr) { const words = inputStr.split(/\s+/); if (words.length < 2) return []; return Array.from({length: words.length - 1}, (_, i) => `${words[i]} ${words[i+1]}`); } // 测试用例 const testStr = "how are you to day"; console.log(getWordPairs(testStr)); // 输出:['how are', 'are you', 'you to', 'to day']
Java
import java.util.ArrayList; import java.util.List; public class WordPairGenerator { public static List<String> getWordPairs(String inputStr) { List<String> pairs = new ArrayList<>(); String[] words = inputStr.split("\\s+"); for (int i = 0; i < words.length - 1; i++) { pairs.add(words[i] + " " + words[i+1]); } return pairs; } public static void main(String[] args) { String testStr = "how are you to day"; System.out.println(getWordPairs(testStr)); // 输出:[how are, are you, you to, to day] } }
内容的提问来源于stack exchange,提问作者Dung Nguyen
相关产品推荐
相关产品推荐

