【问题标题】:Length of String is longer than Characters of String字符串的长度比字符串的字符长
【发布时间】:2012-11-09 07:29:28
【问题描述】:

为什么会这样?

我从另一个类中获取一个字符串以将其与当前字符串进行比较,但是 if 语句不起作用,因为该字符串有问题。当我尝试检查长度时,它们有所不同。这怎么可能?

receivedCom = "去";

  public string checkaction(string receivedCom)
        {

            print ("-------" + receivedCom + "-------" + receivedCom.Length); //Just to show there isnt any white spaces behind or infront --> OUTPUT IS "-------go-------3"
            print (receivedCom + receivedCom.Replace(" ", "").Length); //Tried removing white spaces if there were any --> OUTPUT "go3"
            string x = receivedCom.Remove(receivedCom.Length-1); 
            print (x + " " +x.Length); --> OUTPUT IS "go 2" (Correct lenght, but if still doesnt want to work with it)

            if("go".Equals(x)){
            return "yes";
            }
            else{return "";}
        }

要么发生了一些奇怪的事情,要么我正在失去它。

这是在 CS 脚本中完成的。 (由 Unity 使用。)

更新:

运行 Jon Skeet 提供的代码,这是我的结果

Lenght: 3
receivedCom[0] = 103
receivedCom[1] = 111
receivedCom[2] = 13

更新:我是如何获得“回车”的

void Start () {

        player = GameObject.FindWithTag("Player");
        script = (PlayerScript) player.GetComponent(typeof(PlayerScript));

        Process p = new Process();
        p.StartInfo.FileName = @"F:\ReceiveRandomInput.exe"; //This exe generates random strings like "go" "start" etc as a console application


        p.StartInfo.Arguments = "arg0 arg1 arg2 arg3 arg4 arg5";
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        //add event handler when output is received
        p.OutputDataReceived += (object sender, DataReceivedEventArgs e) => {


        data = e.Data;  //THIS DATA is what i sent though to the other class (one with the carriage return in
        received = true;
        };

        p.Start();
        p.BeginOutputReadLine();
    }

【问题讨论】:

  • 您是否在 删除最后一个字符之前对字符串运行了该测试?
  • 这是一个回车符。你可以删除它,或者 Trim() 字符串
  • 我已经更新了测试结果(为之前的测试编写了一个变量“go”)
  • 我接受它,每次我的控制台应用程序换行时,它都会发送回车。
  • 回车将光标返回到该行的第一个字符,而换行符将光标设置到下一行。 Windows 倾向于使用回车后跟换行符来开始新行。我不确定 CR 本身会对控制台产生什么影响。

标签: c# string if-statement


【解决方案1】:

这怎么可能?

您已经表明没有任何空格。这并不意味着没有不可打印的字符。

最简单的诊断方法是打印出“奇数”的 Unicode 值:

print((int) receivedCom[receivedCom.Length - 1]);

我猜它会是 0,这只是你读取数据的方式中的一个错误。

编辑:当然要显示准确字符串中的内容,只需打印所有内容:

print ("Length: " + receivedCom.Length);
for (int i = 0; i < receivedCom.Length; i++)
{
    print("receivedCom[" + i + "] = " + (int) receivedCom[i];
}

如果您可以将结果编辑到问题中,我们可以取得进展。

【讨论】:

  • 它也可能是第一个或第二个字符,可能更好地循环它?
  • @Esailija:在给出的示例中没有,删除最后一个字符就可以了。
  • @Jon Skeet 我不认为它可以在前面,因为我从后面删除了一些东西,仍然得到“去”这个词?或者我又错了
  • @JonSkeet 我看到的方式是即使删除最后一个字符“它仍然不想使用它”:P
  • @Ruan:这很奇怪 - 111 是 o。你能展示那个案例的全部痕迹吗?
猜你喜欢
  • 2013-02-12
  • 2017-08-19
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
相关资源
最近更新 更多