首页 新闻 会员 周边

我编写的代码怎么实现不了字符串的内容倒置,问题出在哪里,该怎样修改

0
悬赏园豆:5 [待解决问题]

代码如下:

class Program
    {
        static string str = Console.ReadLine();
        static char[] word = str.ToCharArray();
       
        static void Main(string[] args)
        {
           
            foreach (char c in word)
            {
                Console.WriteLine("{0}\n", c);
            }
            for (int i = 0; i <word.Length; i++)
            {
                word[i] = word[word.Length - 1 - i];
                Console.WriteLine(word[i]);
            }
           
            Console.ReadLine();
           
        }
    }

绿光的主页 绿光 | 初学一级 | 园豆:197
提问于:2013-09-07 19:51
< >
分享
所有回答(4)
0

word[i] = word[word.Length - 1 - i];

这句有问题吧,再加一变量

2J | 园豆:159 (初学一级) | 2013-09-08 07:16
0

把字符串分割成数组,然后直接用数组倒序,再拼接~~

不负春光,努力生长 | 园豆:1382 (小虾三级) | 2013-09-08 09:24
0
将:word[i] = word[word.Length - 1 - i]; 加一个中间变量,用来交换数据,第1个转移到最后一个。
幻天芒 | 园豆:37175 (高人七级) | 2013-09-08 10:06
0

 for (int i = 0; i <word.Length; i++)
            {
                word[i] = word[word.Length - 1 - i];
                Console.WriteLine(word[i]);
            }

这个循环中存在问题,将字符串倒置时有字符没保留。如i=0时,直接将word[word.Length - 1 - 0]赋值给word[0],那么字符word[0]被覆盖了。希望能帮到你哈。

木吉他的夏天 | 园豆:202 (菜鸟二级) | 2013-09-08 16:31
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册