【问题标题】:String Split in C# in this Particular Manner以这种特殊方式在 C# 中拆分字符串
【发布时间】:2014-02-26 03:22:55
【问题描述】:

伙计们,我正在从以下查询中获取数据

MySqlCommand cmd = new MySqlCommand("select concat(c1.countryname,' vs ',c2.countryname) as CountryACountryB,r.Description as Round,m.result,m.matchId from matches m left join countries c1 on m.countryId1=c1.countryId left join countries c2 on m.countryId2=c2.countryId left join rounds r on m.roundId=r.roundId where matchId=" + msMatch.SelectedItem.Value, register);

当我检查 i Value 进入 CountryACountryB 时,它的阿根廷与波斯尼亚和黑塞哥维那(例如:)

这是我实现的分割字符串的代码

string fullTeam = dr["CountryACountryB"].ToString();
            string[] names = fullTeam.Split(' ', '-');
            string name = names.First();
            string lasName = names.Last();
            string Final = name + ". " + lasName;

它确实有效,但在阿根廷对波斯尼亚和黑塞哥维那的比赛中

string name = names.First();//Comes as Argentina(Which is Fine)
string lasName = names.Last();//Comes Herzegovina

这就是我想要的方式

string Final = name + ". " + lasName;//Argentina + ". " + Bosnia and Herzegovina

有什么帮助吗??

【问题讨论】:

  • 顺便说一句,这似乎是 SQL 注入攻击的可疑之处,因为您连接 msMatch.SelectedItem.Value 而不是参数化 matchIden.wikipedia.org/wiki/SQL_injection
  • 总是"CountryA vs CountryB" 吗?
  • 好吧,您可以使用正则表达式并查找“ vs. ”,但首先分别返回两个国家/地区名称不是更容易吗?
  • 只有男生才能回答?

标签: c# asp.net string string-split


【解决方案1】:

当您与' vs ' 连接时。您应该使用与拆分相同的字符串。

所以用

string[] names = fullTeam.Split(new string[]{" vs "}, StringSplitOptions.None);

我的个人意见是你不需要连接。只需分别访问countryAcountryB

【讨论】:

  • 嘿@Rimpy:它说[]内的索引数量错误;expected1
  • @SiddharthKoya:只是一个错字。应该是new string[]{" vs "}
  • 谢谢@ChrisSinclair
【解决方案2】:

fullTeam.Split(' ', '-') -> fullTeam.Split(new[]{" vs "}, StringSplitOptions.None);

【讨论】:

  • 我觉得,为了安全起见,您可能想在“vs”(包括空格)上拆分。快速检查一下维基百科的List of Countries 并没有显示任何名称中带有“vs”的内容,但我仍然觉得它很有机会。编辑:哎呀,如果你在查询中组合它,然后再拆分它(这对我来说很奇怪;为什么不只返回两个不同的值?)然后选择一个特殊字符(或字符序列),如 |或 ~ 或 / 保证不会出现在返回的名称中。
  • string[] names = fullTeam.Split(new string[](" vs "), StringSplitOptions.None);工作.. Thnkx 伙计们非常感谢它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
相关资源
最近更新 更多