c# - 如何根据其代码页索引从字符串中删除字符?
问题描述
我正在用 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;
}
}
解决方案
我不得不承认我对问题的根源有误。原来,一些数据还包含几个撇号。那些破坏了目标数据库的 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:我知道这个问题不是应该的。一旦我更多地了解这里应该如何做,我会做得更好。
推荐阅读
- django-rest-framework - 如何使用来自社交身份验证的 JWT 来获取 django.contrib.models.user 的相应用户
- python - 如何找到一列的每个值到具有不同行长的其他数据框的列?
- php - 有没有办法可以在按钮单击时在 PHP 中传递变量?
- loops - 由clang优化的简单循环,如何?
- java - 超级基本问题:如何用 Java 代码制作可执行程序?
- scala - 如果列为空,如何进行透视
- javascript - 使用来自 node_modules 的 SVG
- python - 使用 smtplib 发送邮件在本地部署时有效,但在 swarm 中部署时失败(无法分配请求的地址)
- python - 使用 beautifulsoup 抓取维基百科表格
- javascript - 电子/节点 - 使用 require 和 readFile 的片段使 javascript 失败