C#使用数字和字母转换/拆分字符串

时间:2013-06-19 17:44:02

标签: c# string split numeric letters

我试图将一个String拆分成一个parts数组,并将它们最后组合成一个结果String。 但是当我稍微测试一下时,我收到了一条消息。

按下convert_click:

"NullRefenceException was unhandeled"

Object reference not set to an instance of an object.

这里是主要代码:

    public string []parts { get; set; }
    public string inputStr { get; set; }

    private void inputText_TextChanged(object sender, EventArgs e)
    {
        String inputStr = inputText.ToString(); 
        //example 
        //inputStr = "984, fenceshit2, 0, 1994.56025813, -1592.16428141, 16.105, 0.653280779782, 0.270598520636, 0.653281646552, 0.270598879665, -1";
    }

    private void convert_Click(object sender, EventArgs e)
    {
        String creObj = "CreateObject(";
        String result;
        String[] parts = inputStr.Split(new char[]  { ',' });

        result = creObj +
                 parts[0] + "," +
                 parts[2] + "," +
                 parts[3] + "," +
                 //...up to "parts[10"
                 ");";
        outputText.Text = result; 
        //output(should be in this case): 
        //"CreateObject(984,    1994.56025813,  -1592.16428141,  16.105, 0.653280779782,  0.270598520636,  0.653281646552, 0.270598879665, -1);"
    }

    //If I need to creat a code line in the main Designer.cs, please let me know.

我只想拆分一个String并将它们最终合并为一个字符串并将其发送到一个文本框中。

如果有人想要源代码,请发给我。

2 个答案:

答案 0 :(得分:1)

因为您要将inputText.toString()分配给本地inputStr。在函数inputText_TextChanged中,只需写入

inputStr = inputText.Text;

答案 1 :(得分:0)

当您确实想要分配给公共字符串时,您正在声明输入字符串的本地副本。

而不是

String inputStr = inputText.ToString(); 

这样做:

inputStr = inputText.ToString();