开发者

Check string length and make 2 string out of one (C#)?

I have a string which can be of any length. Now I have to cut this string into 2 parts, each of the 2 parts must only be of length 35. So lets say the original string is of length 50, that makes string1 to be 35 and string2 to be 15.

In case the original strings length is < 35, string2 should stay empty. The whole string parse thing should only take place under a certain circumstance (if condition). The question is, how could I sol开发者_C百科ve this as short as possible?

Thanks :-)


Something like this?

string original = "12345678901234567890123456789012345678901234567890";
string first= "", second= "";

first = original.Substring(0, original.Length < 35 ? original.Length : 35);
if( original.Length > 35) second = original.Substring(35, original.Length < 70 ? original.Length - 35 : 35);


This is not the optimal way to do it as the string will be enumerated twice, but the code is simple so if performance is not an issue here it could be an option:

var part1 = new string(text.Take(35).ToArray());
var part2 = new string(text.Skip(35).Take(35).ToArray());

As Take and Skip handle all the logic this works for texts of less than 35 characters, less than 70 and longer than 70 characters without any additional logic.


What to do if string is greater than 35 x 2 = 70 characters?

string myString = "My long string...";
string firstString;
string secondString;
// if string length is more than 35 characters
if (myString.Length > 35)
{
    // getting first 35 characters
    firstString = myString.Substring(0, 35);
    // getting rest of the string
    secondString = myString.Substring(35);
}
else
{
    firstString = myString;
    secondString = string.Empty;
}


SubString(int, int) - The first parameter is the starting character of the substring while the second parameter is the number of characters.

SubString(int) - The parameter is the starting character of the substring.

string aString = "Some string";
int length = aString.Length;
string partOne;
string partTwo;
partOne = aString.SubString(0
if(length > 35) {
  partOne = aString.SubString(0, 35);
  partTwo = astring.SubString(35);
} else {
  partOne = aString.SubString(0, length);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜