I apologise if this has been asked before, but I can't find it.
How does one concatenate Dim x = {"apple", "banana", "milk"} into a grammatically correct sentence in the easiest way possible?
Function:
Function GetGrammaticalSentence(str as string()) as String
//Do something
Return ret
End Function
Private _ingredients = {"apple", "banana", "milk"}
Private _breakfastString = $"Today, I had {GetGrammaticalSentence(_ingredients)} in a bowl for breakfast"
Sub New()
Console.WriteLine(_breakfastString)
End Sub
Result: Today I had apple, banana and milk in a bowl for breakfast.
CodePudding user response:
This should cover all the bases
Function GetGrammaticalSentence(str As String()) As String
Select Case str.Count
Case 0
Return ""
Case 1
Return String.Concat("an ", str(0))
Case 2
Return String.Join(" and ", str)
Case Else
Return String.Concat("an ", String.Join(", ", str.SkipLast(1)), " and ", str.Last)
End Select
End Function
CodePudding user response:
If the only rules you need to follow are that all words are separated by a comma except for the last word, which should be separated by and
, you can use a simple loop.
Function GetGrammaticalSentence(input As String()) As String
Dim concat As String = input(0) 'start off by capturing the first word
For index = 1 To input.Length - 1 'since we already captured the index 0, start at index 1
If index = input.Length - 1 Then 'if it's the last word in the array, use and
concat = $"{concat} and {input(index)}"
Else 'else, use a comma
concat = $"{concat}, {input(index)}"
End If
Next
Return concat
End Function