c#有一列乱序的字符:a、c、u、b、e、、f、z,排序并按照英文字母表的升序和逆序输出。
时间: 2024-06-16 17:06:47 浏览: 7
要对乱序的字符进行排序,可以使用C#中的Array.Sort方法。以下是对给定字符数组进行排序并按照英文字母表的升序和逆序输出的示例代码:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
char[] chars = { 'a', 'c', 'u', 'b', 'e', 'f', 'z' };
// 升序排序
Array.Sort(chars);
Console.WriteLine("升序排序结果:");
foreach (char c in chars)
{
Console.Write(c + " ");
}
Console.WriteLine();
// 逆序排序
Array.Reverse(chars);
Console.WriteLine("逆序排序结果:");
foreach (char c in chars)
{
Console.Write(c + " ");
}
Console.WriteLine();
}
}
```
输出结果:
```
升序排序结果:
a b c e f u z
逆序排序结果:
z u f e c b a
```
相关问题
用C#写以下程序:输入一行字符,分别统计出其中英文字母、空格、数字和其它 字符的个数。
以下是用C#实现输入一行字符,统计其中英文字母、空格、数字和其他字符个数的程序:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入一行字符:");
string str = Console.ReadLine();
int letterCount = 0, spaceCount = 0, digitCount = 0, otherCount = 0;
foreach (char c in str)
{
if (char.IsLetter(c))
{
letterCount++;
}
else if (char.IsWhiteSpace(c))
{
spaceCount++;
}
else if (char.IsDigit(c))
{
digitCount++;
}
else
{
otherCount++;
}
}
Console.WriteLine("英文字母个数:" + letterCount);
Console.WriteLine("空格个数:" + spaceCount);
Console.WriteLine("数字个数:" + digitCount);
Console.WriteLine("其他字符个数:" + otherCount);
}
}
```
C# list取出指定一列并拼接字符串
假设你有一个 `List` 对象,其中包含多个自定义对象,每个对象都有多个属性。现在你想要从这个 `List` 对象中取出其中一个属性,并将其拼接成一个字符串。可以按照以下方式实现:
```csharp
using System.Collections.Generic;
using System.Linq;
// 定义一个自定义对象
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
// 创建一个包含多个 Person 对象的 List
var persons = new List<Person> {
new Person{Name="Tom", Age=18},
new Person{Name="Jerry", Age=20},
new Person{Name="Lucy", Age=22},
new Person{Name="Lily", Age=25},
};
// 从 List 中取出 Name 属性并拼接成字符串
string result = string.Join(",", persons.Select(p => p.Name));
```
在上面的代码中,我们使用了 LINQ 查询语句来从 `persons` 中选择 `Name` 属性,并使用 `string.Join` 方法将它们拼接成一个字符串。在这个例子中,最终的结果是一个字符串,它包含了所有 `Person` 对象的 `Name` 属性,中间用逗号分隔。