字符串分割超出范围 [英] Index out of bounds on string split

查看:86
本文介绍了字符串分割超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在使用将SQL查询发送到SQL Server 2008的C#表单应用程序.
我有一个应该用来分割更新字符串的函数,因此我可以根据用户打勾的复选框来添加字段.

我很想在此函数中出现错误:

Hi,
I am working on a c# form application which sends sql queries to SQL Server 2008.
I have a function which is supposed to split my update string so I can add fields depending on which checkboxes the user ticks.

I keed getting an error in this function:

private string DivideInTwo(string toBeDivided,string AddedString)
        {
            string[] delimitator = new string[] { "set" };
            string[]  string1=toBeDivided.Split(delimitator,StringSplitOptions.None);
            
            string1[0] = string1[0] + " set ";
/*this is the error line*/string stringFinal = string1[0] +AddedString+ string1[1];

            return stringFinal;
        }



我在这条线上收到错误:



I get the error on this line:

string stringFinal = string1[0] +AddedString+ string1[1];



特别是在string1 [1]部分.

还使用for语句和索引根本没有帮助.

有人知道这是怎么回事吗?

预先谢谢您,

CrinaT.



specifically at the string1[1] part.

also using a for statement and an index didn''t help at all.

Does anyone know what is wrong here?

Thank you in advance,

CrinaT.

推荐答案

我知道出了什么问题.错误恰恰说明了这一点.当您调用split时,不保证您有任何特定数量的元素,在这种情况下,在字符串中找不到分隔符(sic),因此只有一个元素,并且代码会炸毁,因为不会检查它的假设.
I know what''s wrong. It''s exactly what the error says. When you call split, you are not guarenteed to have any specific number of elements, and in this case, your delimitator (sic) is not found in the string, so there''s only one element, and your code blows up because it doesn''t check it''s assumptions.


在访问每个项目之前检查长度.

check length before access each item.

string stringFinal = string.Empty;
string[] delimitator = new string[] { "set" };
string[] strings = toBeDivided.Split(delimitator, StringSplitOptions.None);
if (strings.Length > 1)
{
    stringFinal = string.Format("{0} set {1}{2}", strings[0], AddedString, strings[1]);
}

return stringFinal;


这篇关于字符串分割超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆