很有名的一道编程题.

 

下面是用c#语言实现的.

原理:用格式化字符串的方法动态改变输入值.

代码
1 using System;
2 using System.Text;
3 namespace HelloPrintSelf
4 {
5     class Program
6     {
7         static void Main()
8         {
9             string s = "using System;using System.Text;namespace HelloPrintSelf{ class Program { static void Main()   {   string s =\"%s\"; s = MyPrintf(s, s);Console.Write(s);Console.Read();}    static string MyPrintf(string format, string arg)        {            StringBuilder builder = new StringBuilder(format);            int index = format.IndexOf(\"%s\");            builder.Remove(index, 2);            string escapedStr = Escape(arg);            builder.Insert(index, escapedStr);            return builder.ToString();        }   internal static string Escape(string src)        {            char[] arr = src.ToCharArray();            StringBuilder builder = new StringBuilder();            for (int i = 0; i < arr.Length; i++)            {                if (arr[i] == (char)0x22)                {                    builder.Append((char)0x5c);                    builder.Append(arr[i]);                }                else if (arr[i] == (char)0x5c)                {                    builder.Append((char)0x5c);                    builder.Append(arr[i]);                }                else                {                    builder.Append(arr[i]);                }            }            return builder.ToString();        } }}";
10             s = MyPrintf(s, s);
11             Console.Write(s);
12             Console.Read();
13         }
14 
15         static string MyPrintf(string format, string arg)
16         {
17             StringBuilder builder = new StringBuilder(format);
18             int index = format.IndexOf("%s");
19             builder.Remove(index, 2);
20             string escapedStr = Escape(arg);
21             builder.Insert(index, escapedStr);
22             return builder.ToString();
23         }
24 
25         internal static string Escape(string src)
26         {
27             char[] arr = src.ToCharArray();
28             StringBuilder builder = new StringBuilder();
29             for (int i = 0; i < arr.Length; i++)
30             {
31                 if (arr[i] == (char)0x22)
32                 {
33                     builder.Append((char)0x5c); builder.Append(arr[i]);
34                 }
35                 else if (arr[i] == (char)0x5c)
36                 {
37                     builder.Append((char)0x5c);
38                     builder.Append(arr[i]);
39                 }
40                 else
41                 {
42                     builder.Append(arr[i]);
43                 }
44 
45             } return builder.ToString();
46         }
47     }
48 }
49 
posted on 2010-06-16 12:02  netfuns  阅读(623)  评论(3编辑  收藏  举报