VB.NET实现:将字符串数组拼接为符合语法规则的语句
VB.NET 字符串数组按语法规则拼接实现
我们需要实现一个函数,将字符串数组拼接为符合英文语法的短语,嵌入句子后得到如Today I had apple, banana and milk in a bowl for breakfast.的正确输出。
函数实现
Function GetGrammaticalSentence(str As String()) As String Select Case str.Length Case 0 Return "" Case 1 Return str(0) Case 2 Return $"{str(0)} and {str(1)}" Case Else Return $"{String.Join(", ", str.Take(str.Length - 1))} and {str.Last()}" End Select End Function
逻辑说明
- 空数组:返回空字符串,避免后续拼接出错
- 单个元素:直接返回该元素,无需额外标点
- 两个元素:用
and直接连接,符合英文基础语法 - 三个及以上元素:先将除最后一个元素外的所有项用
,拼接,再通过and连接最后一个元素,匹配常见的英文列举格式
完整测试代码
Private _ingredients = {"apple", "banana", "milk"} Private _breakfastString = $"Today I had {GetGrammaticalSentence(_ingredients)} in a bowl for breakfast." Sub New() Console.WriteLine(_breakfastString) End Sub
运行后控制台输出:
Today I had apple, banana and milk in a bowl for breakfast.
内容的提问来源于stack exchange,提问作者Rabbi Kaii
相关产品推荐
相关产品推荐

