开发者

How to add <br> in string after counting particular characters

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.


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;
}


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


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜