2012-11-08 249 views
0

为什么会发生这种情况?字符串的长度比字符串的长度长

我从另一个类中获取一个字符串以将其与当前字符串进行比较,但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使用。)

UPDATE:

运行由乔恩斯基特提供的代码,这是我的结果

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

UPDATE:我变成了得到一个 “回车”

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

您是否在删除最后一个字符之前在字符串*上运行了该测试? – Esailija

+1

这是一个回车符。你可以删除它,或修剪()字符串 – TheEvilPenguin

+0

我更新了测试结果(有一个变量“去”编码为以前的测试) – Ruan

回答

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]; 
} 

如果你可以编辑的结果放入这个问题,我们可以取得进展。

+0

它可能是第一个或第二个字符,可能更好地循环它? – Esailija

+0

我跑了代码,我得到的数字111 ..所以这将意味着... – Ruan

+0

@Esailija:不是在给出的例子中,删除最后一个字符做了伎俩。 –