Home > Software engineering >  how to split string by position c#
how to split string by position c#

Time:02-22

I have a text string that when it exceeds a specific length, I separate the string into 2 strings, passing the rest of the remaining content to another variable, but I have an exception

Index and length must refer to a location within the string. (Parameter 'length')

My C# code:

        string text = "Hello word jeje";
        if (text.Length > 10)
        { 
            string stringOne = text.Substring(0, 10);
            string stringTwo = text.Substring(11, text.Length); //throw exception
        }

expected result:

string text = "Hello word jeje";
string stringOne = "Hello";
string stringTwo = " jeje";

CodePudding user response:

You have an off-by-one error; you'd need text.Length - 1.

The two-argument version of String.Substring() accepts start and length arguments; you'd need text.Substring(11, text.Length - 11).

However, you can just leave the second argument off for the second half, since the single-argument version of String.Substring() returns a substring to the end of the string.

string stringOne = text.Substring(0, 10);
string stringTwo = text.Substring(11);

CodePudding user response:

How about using the Linq Chunk() extension method?

var test = "Hello World Yeah";
var chunks = test.Chunk(10);
    
foreach (var chunk in chunks)
{
    var subtext = new string(chunk.ToArray());
    Console.WriteLine(subtext);
}

Output:

Hello Worl
d Yeah
  • Related