Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

In chữ cái đầu của mỗi từ trong chuỗi C#

Chuỗi mẫu:

string str = "Never Give Up!";

Tách từ bằng Split(), lấy ký tự đầu bằng Substring(0,1):

Ví dụ hoàn chỉnh

using System;

public class Program
{
    public static void Main()
    {
        string str = "Never Give Up!";
        Console.WriteLine("Chuỗi gốc = " + str);
        Console.WriteLine("Chữ cái đầu mỗi từ...");
        
        string[] strSplit = str.Split();
        foreach (string res in strSplit)
        {
            Console.Write(res.Substring(0, 1));
        }
    }
}

Kết quả

Chuỗi gốc = Never Give Up!
Chữ cái đầu mỗi từ... NGU

Cải tiến: Dùng LINQ: string.Join("", str.Split().Select(w => w[0])). Xử lý khoảng trắng thừa: str.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).