首页 > 解决方案 > 如何根据其代码页索引从字符串中删除字符?

问题描述

我正在用 C# 编写一个 .NET 软件,它应该将数据从一个数据库传输到另一个数据库。代码页 1252的索引大于 127 的每个字符都会导致目标数据库出现问题,因此我想在将这些字符写入目标数据库之前从值(字符串)中删除它们。

我一直在搜索和尝试很多,但到目前为止,我只找到了针对 ASCII 或 UTF 索引执行此操作的解决方案。我需要一个代码页 1252 索引的解决方案。

编辑:这是我迄今为止最接近的方法:

protected string GetSqlValue(string input, bool isStringValue = true)
{
    if (string.IsNullOrWhiteSpace(input)) return "''";
    else
    {
        //TODO: remove all characters with an index greater than 127 in codepage 1252.
        Encoding targetEncoding = Encoding.GetEncoding(1252);
        byte[] tmp = targetEncoding.GetBytes(input);
        for (int i=0;i<tmp.Length;i++)
        {
            if (tmp[i] > 127) tmp = tmp.Where((source, index) => index != i).ToArray();
        }
        input = targetEncoding.GetString(tmp);

        if (isStringValue) return "'" + input + "'";
        else return input;
    }
}

标签: c#stringcharcodepages

解决方案


我不得不承认我对问题的根源有误。原来,一些数据还包含几个撇号。那些破坏了目标数据库的 DDL 和 DML 语句。我还必须防止德语变音符号也被删除。

所以我的方法的最终版本现在看起来像这样:

/// <summary>
/// Gets the SQL value as German characters of codepage 1252.
/// </summary>
/// <param name="input">The string to convert for the target database.</param>
/// <param name="isStringValue">if set to <c>true</c> return encapsulated in single quotation marks.</param>
/// <returns>"''", or the value itself.</returns>
protected string GetSqlValue(string input, bool isStringValue = true)
{
    if (string.IsNullOrWhiteSpace(input)) return "''";
    else
    {
        Encoding targetEncoding = Encoding.GetEncoding(1252);

        // Remove all characters that are not part of codepage 1252.
        input = targetEncoding.GetString(targetEncoding.GetBytes(input));

        // Remove unsupported special characters.
        byte[] tmp = targetEncoding.GetBytes(input);
        for (int i = 0; i < tmp.Length; i++)
        {
            // Don't delete German umlauts.
            if (tmp[i] == 0xc4 /* Ä */ || tmp[i] == 0xe4 /* ä */ || tmp[i] == 0xd6 /* Ö */ || tmp[i] == 0xf6 /* ö */ || tmp[i] == 0xdc /* Ü */ || tmp[i] == 0xfc /* ü */) continue;

            // Delete non German characters and all kind of apostrophes.
            if (tmp[i] >= 0x80 || tmp[i] < 0x20 || tmp[i] == 0x27 || tmp[i] == 0x60) tmp = tmp.Where((source, index) => index != i).ToArray();
        }
        input = targetEncoding.GetString(tmp);

        if (isStringValue) return "'" + input + "'";
        else return input;
    }
}

非常感谢您的帮助。

PS:我知道这个问题不是应该的。一旦我更多地了解这里应该如何做,我会做得更好。


推荐阅读