Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How to break the string in c#

Ex:
C#
Cananyoneshowsmehowtoaddthelinebreak


Expecting :
C#
Cana
            nyon
            esho


I tried
,\n,\r\n, but not working.

What I have tried:

I tried
,\n,\r\n, but not working.
Cana
nyon
esho
wsme
Posted
Updated 18-Feb-16 4:32am
v2
Comments
Patrice T 18-Feb-16 21:05pm    
What do you mean by "break a string"?
Please show input and result as standard C syntax.

What do you mean by "break a string"?
And where are newlines significant?
Strings don't have "breaks" and a newline is just a character or character sequence as far as a string is concerned. It's only when a string is output to a browser, display, or printer that line breaks become relevant - and then it depends on the environment what you do to perform a newline.
For example, outputting to a console:
C#
Console.WriteLine("Cana");
Console.WriteLine("nyon");
and
C#
Console.WriteLine("Cana\nnyon");
are equivelant, and put in two newlines.
But for a browser, you need HTML:
C#
Response.Write("Cana<br />nyon<br />");
Is needed.
For printing, or output to displays via Paint events, it gets even more complex.

Basically, a string isn't an "output-able" object, and it has no concept of a line break - so there is no "one size fits all" answer we can give.
 
Share this answer
 
Use the Environment.NewLine Property like this:

C#
string str = "Cana" + Environment.NewLine + "nyon" + Environment.NewLine + "whatever";
 
Share this answer
 
Is it about splitting into chunks of four characters?
How about this?
C#
string s = "Cananyoneshowsmehowtoaddthelinebreak";
while(s.Length > 4)
{
    Console.WriteLine(s.Substring(0,4));
    s = s.Substring(4);
}
if (s.Length > 0)
{
    Console.WriteLine(s);
}
Cheers
Andi
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900