문자열 계층 구조를 유지하는 구조가 무엇인지 확실하지 않지만 필요한 경우 각 문자열의 자식 문자열을 가져 오는 방법이 있다고 가정 해 봅시다 (예 : '침대'및 '데스크'를 가져올 수 있음) '집').
public const string OPEN_LIST_TAG = "<ul>";
public const string CLOSE_LIST_TAG = "</ul>";
public const string OPEN_LIST_ITEM_TAG = "<li>";
public const string CLOSE_LIST_ITEM_TAG = "</li>";
가 그럼 난 스트링 빌더 같은 것을 사용하여 재귀 적 방법을 만들 것입니다 :
우선은 상수로 태그를 선언 할
/// <summary>
/// Adds another level of HTML list and list items to a string
/// </summary>
/// <param name="str">The string to add</param>
/// <param name="liStrings">The list of strings at this level to add</param>
/// <param name="iTabIndex">The current number of tabs indented from the left</param>
public void GenerateHTML(System.Text.StringBuilder str, List<string> liStrings, int iTabIndex) {
//add tabs to start of string
this.AddTabs(str, iTabIndex);
//append opening list tag
str.AppendLine(OPEN_LIST_TAG);
foreach (string strParent in liStrings) {
//add tabs for list item
this.AddTabs(str, iTabIndex + 1);
//if there are child strings for this string then loop through them recursively
if (this.GetChildStrings(strParent).Count > 0) {
str.AppendLine(OPEN_LIST_ITEM_TAG + strParent);
GenerateHTML(str, this.GetChildStrings(strParent), iTabIndex + 2);
//add tabs for closing list item tag
this.AddTabs(str, iTabIndex + 1);
str.AppendLine(CLOSE_LIST_ITEM_TAG);
}
else {
//append opening and closing list item tags
str.AppendLine(OPEN_LIST_ITEM_TAG + strParent + CLOSE_LIST_ITEM_TAG);
}
}
//add tabs for closing list tag
this.AddTabs(str, iTabIndex);
//append closing list tag
str.AppendLine(CLOSE_LIST_TAG);
}
그리고 별도로 추가 탭을 분리 방법 :
/// <summary>
/// Appends a number of tabs to the string builder
/// </summary>
/// <param name="str">The string builder to append to</param>
/// <param name="iTabIndex">The number of tabs to append to</param>
public void AddTabs(System.Text.StringBuilder str, int iTabIndex) {
for (int i = 0; i <= iTabIndex; i++) {
str.Append("\t");
}
}
다음은 새로운 문자열 작성기로 GenerateHTML을 호출하기 만하면됩니다. 문자열의 첫 번째 수준 및 탭 인덱스를 0으로 설정하고 원하는 것을 제공해야합니다. 어떤 종류의 구조를 사용하고 있는지 확실하지 않았기 때문에 하위 문자열을 가져 오는 기능을 포함하지 않았습니다. 저에게 알려 주시면 솔루션을 적용 할 수 있습니다.
호프가 도움이 되었으면 데인.
mo에있는 코드를 추가하십시오. – Owen
문자열 (예 : '집', '침대', '책상'등)을 유지하기 위해 사용하는 구조는 무엇입니까? – link664