i want to split after 20 characters in a given string and i want to place in another string [Resolved]

Posted by Parcha under C# on 10/4/2011 | Points: 10 | Views : 6195 | Status : [Member] | Replies : 2
Hi
In my applcation for example there are 160 characters or more .... i want to split after 20 characters in next line
if hi karthik is there i want to break after the completion of word.

string str=some 160 characters or more

// and i want to break after 20 characters and iwant to place in another string

plz help me how to split...




Responses

Posted by: Reena_jainy2k1 on: 10/4/2011 [Member] Starter | Points: 50

Up
0
Down

Resolved
Hi,

try this

List<string> output;
while (s.Length > 20)
{
output.Add(s.Substring(0, 20) + "\n");
s.Remove(0, 20);
}
output.Add(s + "\n");
string mynewstring= output.ToArray();

or

You could simply do:

string content = new string(fullString.Take(20));

Take is a LINQ method that works on an IEnumerable<char> (which a string is). The string(char[]) is used to construct a new string which you can then print.

Reena Jain
Project Manager

Parcha, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Niladri.biswas on: 10/10/2011 [Member] Platinum | Points: 25

Up
0
Down
Hi, you can even try with the following too
Solution 1

string newString = string.Empty;
char[] input = "Hi In my applcation for example there are 160 characters or more .... i want to split after 20 characters in next line if hi karthik is there i want to break after the completion of word.".ToCharArray();
int toSplit = 20;
for (int i = 0; i < input.Count(); i++)
{
if (i % toSplit == 0 && i != 0) newString += Environment.NewLine;
newString += input[i].ToString();
}

Solution 2

string newString = string.Empty;
char[] input = "Hi In my applcation for example there are 160 characters or more .... i want to split after 20 characters in next line if hi karthik is there i want to break after the completion of word.".ToCharArray();
int increment = 20;
int start = 0;
int end = input.Count() / increment;

Enumerable
.Range(start, end + 1)
.ToList()
.ForEach(i => newString += input
.Skip(i * 20)
.Take(increment)
.Aggregate("", (a, b) => a + b)
+ Environment.NewLine
);


In all the cases the answer will be


Hi In my applcation
for example there ar
e 160 characters or
more .... i want to
split after 20 chara
cters in next line i
f hi karthik is ther
e i want to break af
ter the completion o
f word.

Hope this helps


Best Regards,
Niladri Biswas

Parcha, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response