Đảo ngược từng từ trong chuỗi nhưng giữ nguyên thứ tự từ. Ví dụ: "Hello World" → "olleH dlroW".
Cách làm (LINQ)
Split(' '): Tách thành mảng từ.Select(s => new String(s.Reverse().ToArray())): Đảo ngược ký tự mỗi từ.string.Join(" ", ...): Nối lại bằng khoảng trắng.
Mã nguồn
using System;
using System.Linq;
class Demo {
static void Main() {
string str = "Hello World";
// Đảo ngược từng từ
string result = string.Join(" ",
str.Split(' ')
.Select(s => new String(s.Reverse().ToArray())));
Console.WriteLine(result);
}
}
Kết quả
olleH dlroW
Phiên bản không dùng LINQ (hiệu năng tốt hơn)
static string ReverseWords(string input) {
string[] words = input.Split(' ');
for (int i = 0; i < words.Length; i++) {
char[] chars = words[i].ToCharArray();
Array.Reverse(chars);
words[i] = new string(chars);
}
return string.Join(" ", words);
}
Lưu ý
Split(' ')không xử lý tốt nhiều khoảng trắng liên tiếp — dùngSplit(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).- LINQ ngắn gọn nhưng cấp phát nhiều đối tượng trung gian — cân nhắc trong vòng lặp nóng (hot path).
- Unicode:
Reverse()hoạt động trênchar(UTF-16 code unit) — có thể hỏng surrogate pair (emoji, ký tự đặc biệt). DùngStringInfocho đúng chuẩn Unicode.