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

Đảo ngược chuỗi (String) trong C#


Để đảo ngược chuỗi, sử dụng phương thức Array.Reverse().

Khởi tạo chuỗi cần đảo:

string str = "Amit";

Chuyển chuỗi thành mảng ký tự:

char[] ch = str.ToCharArray();

Gọi phương thức Reverse():

Array.Reverse(ch);

Ví dụ

using System;
namespace Demo {
    class Program {
        static void Main(string[] args) {
            string str = "Amit";
            char[] ch = str.ToCharArray();
            Array.Reverse(ch);
            foreach (var items in ch) {
                Console.WriteLine(items);
            }
            Console.ReadLine();
        }
    }
}