String的长度比String的字符长

时间:2012-11-08 22:43:48

标签: c# string if-statement

为什么会这样?

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

receivedCom =“go”;

  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();
    }

1 个答案:

答案 0 :(得分:2)

  

这怎么可能?

你已经证明没有任何空白。这并不意味着没有不可打印的角色。

最简单的诊断是打印出“奇数”的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];
}

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