Description
XML中定义一个字符串<X>为一个开始标号,而</X>表示一个结束标号,其中X为一个小写字母,标号之间存在附属关系。
定义一个标准的XML语言为:
1. 一个空串是一个XML语句。
2. 若S为XML语句,则S’ = <X>S</X>也为XML语句。
3. 若S1、S2都是XML语句,则S1+S2也为XML语句。
现给一段XML语句,任务是将这段XML语言按照格式输出。
1. 每个标号独占一行。
2. 输出时下一层的标号需要比上一层的标号多2个空格。
Input
输入数据包括多组数据,每组数据包括一行,每行有一段非空XML语句,长度不超过200。
Output
每组数据按照格式,输出这段XML语句。
Sample Input
<a><b><c></c></b></a>
<a><b></b><d><c></c></d></a>
Sample Output
<a>
<b>
<c>
</c>
</b>
</a>
<a>
<b>
</b>
<d>
<c>
</c>
</d>
</a>
题目链接:http://edu.freefcw.com/problem/show/1592
这题简单,直接上代码:
#include <stdio.h>
#define MAX 201
void parse(char *s)
{
int level = 0;
int index = 0;
int i, j, start, end;
char temp[10];
while (s[index] != '\0')
{
if (s[index] == '<')
{
start = index;
end = -1;
}
else if (s[index] == '>')
{
end = index;
}
if (end != -1)
{
if (s[start + 1] != '/')
{
for (i = 0; i < 2 * level; ++i)
{
temp[i] = ' ';
}
temp[i] = '\0';
printf("%s", temp);
for (i = start, j = 0; i <= end; ++i, ++j)
{
temp[j] = s[i];
}
temp[j] = '\0';
printf("%s", temp);
++level;
}
else
{
--level;
for (i = 0; i < 2 * level; ++i)
{
temp[i] = ' ';
}
temp[i] = '\0';
printf("%s", temp);
for (i = start, j = 0; i <= end; ++i, ++j)
{
temp[j] = s[i];
}
temp[j] = '\0';
printf("%s", temp);
}
putchar('\n');
}
++index;
}
}
int main(void)
{
char str[MAX];
while (scanf("%s", str) != EOF)
{
parse(str);
}
return 0;
}