2012-11-08 248 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:不是在給出的例子中,刪除最後一個字符做了伎倆。 –