[新手提问]c#中对字符串的判断和处理的操作

默无言 2012-09-02 02:42:14
项目:从excel表获取指定数据导入到sql里面
问题1:其中有个chengji 在sql为float 类型,有excel中可能会有+90/-5的写法,如何判断是不是符合要求?
问题2:如果判断不符合float类型,如何将+90/-5处理为 90-5=85 ?
...全文
182 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
string test = @"+5又很-9";
float chengji = 0;
float.TryParse(test, out chengji);
if (chengji == 0)
{
string pattern_match = @"^([+-]\d+/?)+$";
if (Regex.IsMatch(test, pattern_match))
{
string pattern_com = @"([+-])(\d+(\.\d+)?)";
Regex.Matches(test, pattern_com).Cast<Match>().ToList().ForEach(a =>
{
if (a.Groups[1].Value.Equals("+"))
{
chengji += float.Parse(a.Groups[2].Value);
}
else
{
chengji -= float.Parse(a.Groups[2].Value);
}
});
}
else
{
MessageBox.Show("格式错误");
}
}
宏尘 2012-09-03
  • 打赏
  • 举报
回复
我晕,又打印输错了:正确应该是 dd="98-25=73"
宏尘 2012-09-03
  • 打赏
  • 举报
回复
最后打印输错了:正确应该是 dd="98-25=75"
宏尘 2012-09-03
  • 打赏
  • 举报
回复
定义一个函数专门来处理这个:
private string GetStrExpression(string str){

str = str.Trim();
string[] ops = str.Split('/');
int op1Int = int.Parse(ops[0].Trim()),
op2Int = int.Parse(ops[1].Trim());//获得2个操作数(整型)
string op2sys = op2Int > 0 ? "+" : "";
string result = string.Format("{0}{1}{2}={3}", op1Int, op2sys, op2Int, op1Int + op2Int);
return result;
}
测试 string dd= GetStrExpression("+98/-25");
结果 dd="98-25=85"
默无言 2012-09-02
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]

C# code
string test = @"+90/-5";
float chengji=0;
float.TryParse(test,out chengji);
if (chengji == 0)
{
string pattern_com = @"([+-])(……
[/Quote]

如果string test =“+5又很-9”;
应该是报错,实际返回是-4;
这个应该处理呢?
renjunjun 2012-09-02
  • 打赏
  • 举报
回复
判断前面没有=号的话
Excel.cell[1,1] = "=" + Excel.cell[1,1]
  • 打赏
  • 举报
回复
string test = @"+90/-5";
float chengji=0;
float.TryParse(test,out chengji);
if (chengji == 0)
{
string pattern_com = @"([+-])(\d+(\.\d+)?)";
Regex.Matches(test, pattern_com).Cast<Match>().ToList().ForEach(a => {
if (a.Groups[1].Value.Equals("+"))
{
chengji += float.Parse(a.Groups[2].Value);
}
else
{
chengji -= float.Parse(a.Groups[2].Value);
}
});
}
//此时 chengji=85
默无言 2012-09-02
  • 打赏
  • 举报
回复
有没有一起练手的定点儿代码参考下
默无言 2012-09-02
  • 打赏
  • 举报
回复
新手,思路有了,但不会代码
bdmh 2012-09-02
  • 打赏
  • 举报
回复
这东西别问我们,你自己知道表示什么意思,那就按照你的规则拆分出来就好了,正则可以拆分,普通字符串indexof+substring都可以

110,499

社区成员

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

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

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