相关疑难解决方法(0)

如何从字符串中间执行对文化敏感的"启动"操作?

我有一个相对模糊的要求,但感觉应该可以使用BCL.

对于上下文,我正在Noda Time中解析日期/时间字符串.我为输入字符串中的位置维护一个逻辑光标.因此,虽然完整的字符串可能是"2013年1月3日",但逻辑光标可能位于"J".

现在,我需要解析月份名称,将其与文化的所有已知月份名称进行比较:

  • 文化敏感
  • 不区分大小写
  • 只是从光标的角度来看(不是更晚;我想看看光标是否"看着"候选月份名称)
  • 很快
  • ......之后我需要知道使用了多少个字符

当前的代码做这个工作通常使用CompareInfo.Compare.它实际上是这样的(仅用于匹配部分 - 在真实的东西中有更多的代码,但它与匹配无关):

internal bool MatchCaseInsensitive(string candidate, CompareInfo compareInfo)
{
    return compareInfo.Compare(text, position, candidate.Length,
                               candidate, 0, candidate.Length, 
                               CompareOptions.IgnoreCase) == 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,这取决于候选人和我们比较的区域长度相同.大部分时间都很好,但在某些特殊情况下并不好.假设我们有类似的东西:

// U+00E9 is a single code point for e-acute
var text = "x b\u00e9d y";
int position = 2;
// e followed by U+0301 still means e-acute, but from two code points
var candidate = "be\u0301d";
Run Code Online (Sandbox Code Playgroud)

现在我的比较会失败.我可以用IsPrefix: …

.net string unicode

105
推荐指数
3
解决办法
5856
查看次数

由文化敏感的String.IndexOf方法匹配的子字符串长度

我尝试编写一种文化感知字符串替换方法:

public static string Replace(string text, string oldValue, string newValue)
{
    int index = text.IndexOf(oldValue, StringComparison.CurrentCulture);
    return index >= 0
        ? text.Substring(0, index) + newValue + text.Substring(index + oldValue.Length)
        : text;
}
Run Code Online (Sandbox Code Playgroud)

但是,它在Unicode组合字符上窒息:

// \u0301 is Combining Acute Accent
Console.WriteLine(Replace("déf", "é", "o"));       // 1. CORRECT: dof
Console.WriteLine(Replace("déf", "e\u0301", "o")); // 2. INCORRECT: do
Console.WriteLine(Replace("de\u0301f", "é", "o")); // 3. INCORRECT: do?f
Run Code Online (Sandbox Code Playgroud)

为了修复我的代码,我需要知道在第二个例子中,String.IndexOf只匹配一个字符(é),即使它搜索了两个(e\u0301).同样,我需要知道在第三个例子中,String.IndexOf匹配两个字符(e\u0301),即使它只搜索了一个(é).

如何确定匹配的子字符串的实际长度String.IndexOf

注意:执行Unicode规范化text和 …

.net c# unicode substring

14
推荐指数
1
解决办法
618
查看次数

将特殊字符转换为正常

我需要一种方法来转换像这样的特殊字符:

Helloæ

正常人物.所以这个词最终会成为Helloae.到目前为止,我已经尝试过HttpUtility.Decode,或者将UTF8转换为win1252的方法,但没有任何效果.是否有一些简单而通用的东西可以完成这项工作?

谢谢.

编辑

我尝试使用OC上的帖子来实现这两种方法.这是方法:

public static string ConvertUTF8ToWin1252(string _source)
{
    Encoding utf8 = new UTF8Encoding();
    Encoding win1252 = Encoding.GetEncoding(1252);

    byte[] input = _source.ToUTF8ByteArray();
    byte[] output = Encoding.Convert(utf8, win1252, input);

    return win1252.GetString(output);
}

// It should be noted that this method is expecting UTF-8 input only,
// so you probably should give it a more fitting name.
private static byte[] ToUTF8ByteArray(this string _str)
{
    Encoding encoding = new UTF8Encoding();
    return encoding.GetBytes(_str);
}
Run Code Online (Sandbox Code Playgroud)

但它没有奏效.字符串保持不变.

c# asp.net-mvc character-encoding special-characters

3
推荐指数
1
解决办法
9925
查看次数