【问题标题】:Text Split and Text Matching in c#c#中的文本拆分和文本匹配
【发布时间】:2014-09-27 10:40:48
【问题描述】:

它在比较文本时非常简单,但我一直在比较两个文本。 在 C# 中,我创建了一个函数 splitText 将文本拆分为定义数量的字符,然后将拆分后的文本分配给一个字符串变量,然后与另一个字符串进行比较,但比较不起作用。

这里是 splitText 函数

private string splitText(string Text, int startingIndex, int totalCharacters)
        {
            string s = "";
            char[] str = new char[100];
            int count = 0;
            for (int i = startingIndex; i <= totalCharacters; i++)
            {
                str[count++] = Text[i];

            }
            s = new string(str);
            return s;
        }

这是我比较字符串但不起作用的代码

private void button1_Click(object sender, EventArgs e)
        {
            string s = splitText("Khuram Jan", 0, 2);
            if (s.Equals("Khu"))
            {
                MessageBox.Show("I have done");
            }
            else
            {
                MessageBox.Show("Does not compare");
            }
        }

我还显示了字符串 s 值,它显示了我 Khu,但它不起作用在 if 条件下,总是执行 else 部分。我测试了很多,但没有解决这个问题。

【问题讨论】:

    标签: c#


    【解决方案1】:

    您的代码将名为totalCharacters 的变量视为endIndex。但真正的问题是您返回一个长度为 100 的字符串,其中前 3 个字符为 Khu。改为返回new string(str, 0, count)

    【讨论】:

    • 但问题是如何使用动态字符数组,即 char[] str = new str[totalCharacters] 但它给了我例外。
    • 非常感谢 Remus Rusano 帮助我,现在可以了,
    【解决方案2】:

    问题是,您没有得到准确的图表长度字符串返回值。在您的情况下,您将返回 "Khu\0\0\0...."

    修改后的行是

    char[] str = new char[totalCharacters+1];
    

    顺便说一句,你也可以使用following!

     string s1 = "Khuram Jan".Substring(0, 3);
    

    【讨论】:

    • 非常感谢,我明白我在哪里做错了,感谢您提供有价值的 cmets
    猜你喜欢
    • 2013-02-07
    • 2019-07-29
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多