string和int类型转换问题

buyue__ 2011-06-22 11:49:48
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
StreamReader sr=new StreamReader("d:\\1.txt");
string line="";
string[] a;
line=sr.ReadToEnd();
a=line.Split(',');
for(int j=a.Length-1;j>=0;j--)
{
for (int i = 0; i < j; i++)
{
if (int.Parse(a[i]) > int.Parse(a[i + 1]))
{
int b = a[i];
a[i] = a[i + 1];
a[i + 1] = b;
}
}
}
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}


}
}
}

错误 1 无法将类型“string”隐式转换为“int”
错误 2 无法将类型“int”隐式转换为“string”

怎样改??
...全文
65 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
暖枫无敌 2011-06-22
  • 打赏
  • 举报
回复

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
StreamReader sr=new StreamReader("d:\\1.txt");
string line="";
string[] a;
line=sr.ReadToEnd();
a=line.Split(',');
for(int j=a.Length-1;j>=0;j--)
{
for (int i = 0; i < j; i++)
{
if (int.Parse(a[i]) > int.Parse(a[i + 1]))
{
int b = int.Parse(a[i]);
int.Parse(a[i]) = int.Parse(a[i + 1]);
int.Parse(a[i + 1]) = b;
}
}
}
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}


}
}
}
porschev 2011-06-22
  • 打赏
  • 举报
回复

首先确定 string[] a里是可转为int的有效格式吗?

如果是。。。

int b = a[i]; //首先这里错了。。。b是int型的。。。a[i]是string类型的
a[i] = a[i + 1];
a[i + 1] = b; //这里也错了。。。a[i+1]是string类型的。。。。b是int类型的。。。

Convert.ToXXX()做类型转换
ghost5216 2011-06-22
  • 打赏
  • 举报
回复
string s="1";
int i=2;

string ==> int
int j;
if(Int32.TryParse(s,out j))
{
//转换成功
}

int ==> string
string ss = i.ToString();


lihanbing 2011-06-22
  • 打赏
  • 举报
回复
string b = a[i];
a[i] = a[i + 1];
a[i + 1] = b;

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧