如何在asp.net c# html中显示文本之间的空格

发布于 2024-10-27 19:23:36 字数 310 浏览 5 评论 0原文

我有一个奇怪的问题,我直接从数据库获取数据到数据源。数据通过链接按钮绑定在中继器中。

我遇到的问题是数据库中的数据可能在字符串中间有多个空格,但是当显示在前端时仅显示空格。经过思考,这是删除空格的标准 HTML 行为,我会假设 ASP.NET 会通过网页的呈现来处理此问题。还发生的情况是,当报表导出到 Excel 时,它只有 1 个空格,而不是两个。

示例:

2 个空格:“南非   -   开普敦”
单个空间:“南非 - 开普敦”

这是一个无关紧要的示例,但我的数据对多个空间有实际用途。

I have a weird problem, I am getting data straight from the database into a data source. The data is binded in a repeater with link buttons.

The problem I am having is that the data in the database might have multiple spaces in the middle of the string however when being displayed on the front end only space is being shown. After thinking about it this is standard HTML behavior to remove spaces, I would have assumed that asp.net would have handled this with the rendering of the webpage. What is also happening is that when reports are exported to excel it only has 1 space instead of two.

Example:

2 spaces: "South Africa   -   Cape Town"
single spaces: "South Africa - Cape Town"

This is an irrelevant example but my data has real use for multiple spaces.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔嚣张 2024-11-03 19:23:36

您可以用   替换空格,如下所示:

string result = myString.Replace(" ", " ");

这将导致 HTML:

"South Africa  -  Cape Town"

它将用两个空格正确呈现。

You could replace the spaces with  , like this:

string result = myString.Replace(" ", " ");

That would result in the HTML:

"South Africa  -  Cape Town"

Which would render correctly with two spaces.

走野 2024-11-03 19:23:36

最终执行了以下操作:

    Regex spaceRegex = new Regex("\\s{2,}");

    //Only replace subsequent spaces, not all spaces. For example, 
    //"   " (three spaces) becomes "   " (1 space, 2 non-breaking spaces).
    MatchEvaluator matchEvaluator = delegate(Match match)
    {
        StringBuilder spaceStringBuilder = new StringBuilder(" ");
        for (int i = 0; i < match.Value.Length - 1; i++)
        {
            spaceStringBuilder.Append(" ");
        }
        return spaceStringBuilder.ToString();
    };

    return spaceRegex.Replace(server.HtmlEncode(value), matchEvaluator);
}

Ended Up doing the following:

    Regex spaceRegex = new Regex("\\s{2,}");

    //Only replace subsequent spaces, not all spaces. For example, 
    //"   " (three spaces) becomes "   " (1 space, 2 non-breaking spaces).
    MatchEvaluator matchEvaluator = delegate(Match match)
    {
        StringBuilder spaceStringBuilder = new StringBuilder(" ");
        for (int i = 0; i < match.Value.Length - 1; i++)
        {
            spaceStringBuilder.Append(" ");
        }
        return spaceStringBuilder.ToString();
    };

    return spaceRegex.Replace(server.HtmlEncode(value), matchEvaluator);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文