1

I want to display description of product in gridview, but i want to display only 15 characters on one line, I want to break it after 15 characters, I have written countchar function as follows:

public int CountChars(string value)
{

    bool lastWasSpace = false;

    foreach (char c in value)
    {
        result++;
        lastWasSpace = false;
    }
    return result;
}

and called function as:

string description="sdfsdfsd sdfsdf sdfsdf asdfsa dfsda safsaf sdfdf sdfs sdfsdf sdff sdf ";

CountChars(description);

And i want to check:

if(result>15)
{
 after every 15 characters i want to break the line. 
}

Please tell me how to do this.

RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262
tina
  • 11
  • 2

3 Answers3

0
public string AddSpaces(string value) {
    int result = 0;
    string new_value = "";
    foreach (char c in value)
    {
        result++;
        new_value += c.ToString();
        if ( result == 15 ) { 
            new_value += "<br />"; 
            result = 0; 
        }
    }
    return new_value;
}
Andrew Jackman
  • 13,781
  • 7
  • 35
  • 44
0
if (value.Length > 15)
{
    StringBuilder sb = new StringBuilder();
    for (i = 0; i < value.Length; i+=15)
        sb.Append(value, i, Math.Min(value.Length - i, 15)).Append("<br/>");
    value = sb.ToString();
}

Not tested

Guillaume
  • 12,824
  • 3
  • 40
  • 48
0

Using the method found here (to split the string)

string str = "111122223333444455";
int chunkSize = 4;
string tmp = String.Join("<br />", str.ToCharArray().Select((c, i) => new { Char = c, Index = i }).GroupBy(o => o.Index / 4).Select(g => new String(g.Select(o => o.Char).ToArray())).ToList());
Console.WriteLine(tmp);

It produces the following result :

1111<br />2222<br />3333<br />4444<br />55
Community
  • 1
  • 1
Shimrod
  • 3,115
  • 2
  • 36
  • 56