ขั้นแรก สร้างรายการ -
List list = new List();
สตริงที่นี่คือ "xyz" ซึ่งเราจะพบรายการย่อย ในขณะที่วนลูป เราจะประกาศรายการอื่น ซึ่งจะสร้างรายการย่อยในทุกการวนซ้ำจริง -
for (int i = 1; i < str.Length; i++) {
list.Add(str[i - 1].ToString());
List newlist = new List();
for (int j = 0; j < list.Count; j++) {
string list2 = list[j] + str[i];
newlist.Add(list2);
}
list.AddRange(newlist);
} ต่อไปนี้เป็นรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
string str = "xyz";
List list = new List();
for (int i = 1; i < str.Length; i++) {
list.Add(str[i - 1].ToString());
List newlist = new List();
for (int j = 0; j < list.Count; j++) {
string list2 = list[j] + str[i];
newlist.Add(list2);
}
list.AddRange(newlist);
}
list.Add(str[str.Length - 1].ToString());
list.Sort();
Console.WriteLine(string.Join(Environment.NewLine, list));
}
}
} ผลลัพธ์
x xy xyz xz y yz z