2015-09-25 25 views
-1
public string completeHour(string theTime) 
    { 
     string total=""; 
     string[] timeArray = theTime.Split(new[] { ":" }, StringSplitOptions.None); 

     string h = timeArray[0]; 

     string i = timeArray[1]; 
     string j = timeArray[2]; 
     MessageBox.Show(h + "+" + i + "+" + j); 

     if (h == " " || i == " " || j == " ") 
     { 
      if (h == " ") 
      { 
       h = "00"; 
       total = (String.Concat("00",theTime)).Trim(); 
       MessageBox.Show(total); 
      } 
      else if (i == " ") 
      { 
       i = "00"; 
       total = timeArray[0] + i + timeArray[2]; 
       //MessageBox.Show("m-=" + total); 
      } 
      //else if (j == "") 
      //{ 
      // j = "00"; 
      // theTime = timeArray[0] + timeArray[1] + j; 
      // MessageBox.Show("s-=" + theTime); 
      //} 
     } 
     return total; 
    } 

串之间的空格为什么total00 :52:04(例如),而不是00:52:04这是应该是什么?为什么它会出现concatened C#

+4

因为'theTime'以空格开头。 –

+1

此外这行:'if(h ==“”|| i ==“”|| j ==“”)'实际上是无用的。 – Tarec

+2

请在提问前使用调试器。 –

回答

2

如果你想确保没有开头或结尾的白色字符,你可以调用

string h = timeArray[0].Trim(); 

然后,而不是检查对" "的价值,你可以把它比作String.Empty或致电h.IsNullOrEmpty() 。 但是,我强烈建议您使用更简单的方法,使用DateTime对象。

DateTime timeObject; 
DateTime.TryParse(theTime, out timeObject); 

,然后只是HourMinuteSecond性工作。通过这种方式,您可以远离自定义分析,并使您的代码更加面向对象,从而更易于阅读,而不是玩弄多个字符串对象。

2
避免这种情况是使用修剪

的最佳方式()指定值时下面两行合计:

total = (String.Concat("00",theTime.Trim())).Trim(); 
. 
. 
. 

total = timeArray[0].trim() + i + timeArray[2].Trim(); 
0

虽然我使用的是MaskedTextBox中我并没有定义一个定制模板等等,任何地方(我认为)系统假定'theTime'是DateTime的类型。 因此,例如,String.Concat(“00”,theTime)的结果是'00:32:99'。 我已经通过使用变量h,i和j而不是theTime来解决它。 使用DateTime变量未被占用,因为我想允许用户插入小时或分钟的NULL值。