您的位置:首页 > 其它

一个小小的问题

2011-08-12 10:41 162 查看
今天在浏览CSDN .NET模块的时候,看到了一个蛮有意思的问题:

楼主提出的第一个问题" string str = "1,2,6"; 要在指定的索引后面加上3,最终输出的操作数据为:1,2,3,6;“

我的解法是:

string str="1,2,6";

str=str.Insert(3, ",3");

Console.WriteLine(str);

输出结果为:1,2,3,6;

满足楼主的要求:但楼主在后面才说出了其真实的问题:

题:string str="1,2";

string str1="1,3,4,5";输出结果为:1,2,3,4,5;

思考了一会儿,觉得这个问题还可以,于是就行动了起来,最后调试的结果却不是预设的那样;

问题就出现在了两个数据没有进行比对,我就纳闷了;

我的算法:首先、将这两个字符串分别进行分割;并且将str1添加到ArrayList类中去;

然后用str与ArrayList类中的数据进行比较,最后,进行排序、输出;

原本认为这样可以实现,但是,输出的结果却让我感到意外。

using System;

using System.Collections.Generic;

using System.Text;

using System.Data.SqlClient;

using System.IO;

using System.Media;

using System.Runtime;

using System.Collections;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

string str = "1,2,6";

str=str.Insert(3, ",3");

string str1 = "1,3,4,5,";

Console.WriteLine(str);

///分割操作

///

try

{

string[] b = str1.ToString().Split(',');

string[] a = str.ToString().Split('.');

ArrayList array = new ArrayList(a);

if (b.Length > 0)

{ ///判断是否有数据。

///有数据,那么现在就来进行数据比对。

///

for (int i = 0; i < str1.Length; i++)

{

if (array.Contains(str[i]) == false)

{ ///说明不在,那么就可以加入

array.Add(str[i]);

}

}

///现在就将这些数据进行排序操作.

///

array.Sort();

///输出数据操作。

///

string value = "";///保存最后的数据.

///

for (int i = 0; i < array.Count; i++)

{

value = value + array[i].ToString();

}

Console.WriteLine(value);

}

else

{

Console.WriteLine("请输入相关数据!");

}

Console.WriteLine(a);

}

catch(Exception ex){

Console.WriteLine(ex.Message);

}

}

}

}

如果有大牛路过,就请指教一下,菜鸟我一定不胜感激。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: