2012-10-25 30 views
2

我有一條消息,它說287個字符長。我需要在160個字符之後將它分成兩部分,但我的代碼仍然無法工作。我搜索了很多,並嘗試了很多不同的解決方案,但沒有像我所期望的那樣工作。在我的腦海中,這是一個簡單的解決方案,但在實踐中,它使我做了噩夢!使用子串超出範圍拆分字符串

// a check is done to ensure the message is > 160 in length.  
string _message; 
_message = "this is my long message which needs to be split in to two string after 160 characters. This is a long message. This is a long message. This is a long message. This is a long message. This is a long message."; 

string message1 = _message.Substring(0,160); 
string message2 = _message.Substring(161,_message.Length); 

上面根本不起作用 - 雖然給我第二個子字符串的異常錯誤。

任何人都可以幫忙嗎?該消息永遠不會超過320個字符。

回答

7

String.Substring確實從第一個參數開始並具有第二個參數的長度。你已經通過message.Length作爲第二個參數,這是行不通的。

可以使用overload with just one parameter(從開始到結束):

string firstPart = _message.Substring(0,160); 
string rest = _message.Substring(160); 

拋出ArgumentOutOfRangeException 如果從startIndex比字符串的長度小於零或更大。

演示:http://ideone.com/ZN2BlM

+1

-1當你先拿下160個物品,項目,你的開始索引是160不是161. –

+0

@SaeedAmiri:更正,謝謝。 –

+0

和downvote刪除 –

4
string message1 = _message.Substring(0,160); 
string message2 = _message.Substring(160,_message.Length - 160); 

請參閱This使用兩個參數子字符串。

6

對於第二行只是用

string message2 = _message.Substring(160); 

如果你的字符串可以爲小於160個字符,你應該檢查這一點。

+1

-1第二種情況起始索引應該是160而不是161 –

+1

@SaeedAmiri相當正確。我看到你自己也犯了同樣的錯誤:) – podiluska

+0

和我的downvote被刪除;) –

1

還有就是不走lenght參數,但只是去字符串的結尾String.Substring function的過載。您可以通過以下方式簡化代碼:

string message1 = _message.Substring(0,160); 
string message2 = _message.Substring(160); 
1

Substring方法的第二個參數會從_message中接收您希望採用的數字或字符。相反,這樣做:

string message1 = _message.Substring(0,160);
string message2 = _message.Substring(160,_message.Length-160);

Substring method in C#

+0

@Saeed Amiri,糾正以及;) –

+0

無論如何,我沒有downvote你。在撰寫評論時,我只提出了兩個可用的答案,通知他們修正錯誤,不要將錯誤的答案與OP混淆,並且在糾正答案後刪除了答案。 –

+0

嗯......我猜我不幸運 –

0

根據http://msdn.microsoft.com/en-us/library/aa904308(v=vs.71).aspx功能有以下的足跡:子(INT啓動)或子(INT開始,INT長度)

這意味着你的方式重新調用它說:從位置160開始複製,然後繼續字符串的總長度。 所以,如果你的字符串是287個字符長,那麼你通過告訴它

字符串消息2 = _message.Substring(161,_message.Length);

在位置161處開始複製,並繼續處理以下287個字符。在這種情況下,字符串必須是161 + 287個字符,這是導致錯誤的原因。

您應該使用:

串_message;
_message =「這是我的長信息,需要在160個字符後分成兩個字符串,這是一條長信息,這是一條長信息,這是一條長信息,這是一條長信息。長信息「。 string message1 = _message.Substring(0,160);
string message2 = _message.Substring(message1.Length,_message.Length - message1.Length);

這將導致消息的長度爲287-160 = 127。

+0

@SaeedAmiri:你也贊成這個嗎? – Daneo

+0

當我倒下了某人的時候,通常我正在寫我的理由(除非是非常明確的情況),對於你的回答,不,我沒有降低你的評價,但無論如何,詢問某人是不是很好,看看是否是downvoter或不,恕我直言,這是無禮的。 –

+0

@SaeedAmiri道歉,但我沒有看到其他人做了downvote。沒有侮辱的意思。 – Daneo