Write the following code using c #,3. Write a method that takes an argument (a string array) and print each item on a single line separated by a space. From your main, call this method with poem as argument.5. In your main method use the method in question 3 to display the poem array, then use the Array.Sort() method to sort the poem array and then again call the appropriate method to print it
时间: 2024-01-22 17:03:51 浏览: 168
Sure, here is the C# code for your requirements:
```csharp
using System;
class Program {
static void PrintStringArray(string[] arr) {
foreach (string str in arr) {
Console.Write(str + " ");
}
Console.WriteLine();
}
static void Main(string[] args) {
string[] poem = { "Twinkle", "twinkle", "little", "star,", "How", "I", "wonder", "what", "you", "are!" };
// Print the unsorted poem
Console.WriteLine("Unsorted Poem:");
PrintStringArray(poem);
// Sort the poem
Array.Sort(poem);
// Print the sorted poem
Console.WriteLine("Sorted Poem:");
PrintStringArray(poem);
}
}
```
Explanation:
- The `PrintStringArray()` method takes a string array as an argument and prints each item on a single line separated by a space.
- In the `Main()` method, we create a string array called `poem` with the poem lines.
- We then call the `PrintStringArray()` method with `poem` as the argument to print the unsorted poem.
- Next, we use the `Array.Sort()` method to sort the `poem` array.
- Finally, we call the `PrintStringArray()` method again with the sorted `poem` array to print the sorted poem.
阅读全文