Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中替换文本,同时保持大小写完整#_C#_String_Replace_Case - Fatal编程技术网

C# 在C中替换文本,同时保持大小写完整#

C# 在C中替换文本,同时保持大小写完整#,c#,string,replace,case,C#,String,Replace,Case,我有一组句子需要用来替换,例如: abc => cde ab df => de ... 我有一个文本,可以在其中进行更改。 然而,我并没有办法事先知道的情况下说的文字。 例如,如果我有: A bgt abc hyi. Abc Ab df h 我必须更换并获得: A bgt cde nyi. Cde De h 或尽可能接近该值,即保持箱子 编辑:由于我发现这方面有很多困惑,我将尝试澄清一点: 我在问一种在更换帽子后保留帽子的方法,但我认为这种方法没有很好地通过(没有很好地解释th

我有一组句子需要用来替换,例如:

abc => cde
ab df => de
...
我有一个文本,可以在其中进行更改。 然而,我并没有办法事先知道的情况下说的文字。 例如,如果我有:

A bgt abc hyi. Abc Ab df h
我必须更换并获得:

A bgt cde nyi. Cde De h
或尽可能接近该值,即保持箱子

编辑:由于我发现这方面有很多困惑,我将尝试澄清一点:

我在问一种在更换帽子后保留帽子的方法,但我认为这种方法没有很好地通过(没有很好地解释thaat需要什么),所以我将用真实的话给出一个更现实的例子

把它想象成一个闲聊,用他们的中文名字来代替表达,所以如果我映射:

didn't achieve success => failled miserably
然后,我得到设置作为输入:

As he didn't achieve success, he was fired
我会得到

As he failled miserably, he was fired
但如果没有被资本化,那么失败也会被资本化,如果成就或成功被资本化,那么悲惨的是,如果任何人有超过1个字母被资本化,那么它的对应字母也会被资本化

我的主要可能性是(我真正想考虑的)

  • 只有第一个单词的第一个字母大写
  • 每个单词只有第一个字母大写
  • 所有字母大写
如果我能处理好这三个问题,我想这已经是可以接受的了——这是比较容易的问题——当然,如果可行的话,一个更深入的解决方案会更好


有什么想法吗?

您可以使用指定的
StringComparison.CurrentCultureInoRecase
来查找匹配项。在这一点上,一个字符一个字符的替换就可以完成交换。可以通过检查源字符,然后根据需要在目标字符上使用或来处理大小写。

一次替换一个字符并使用

if(currentChar.ToString() == currentChar.ToUpper(currentChar).ToString())
{
   //replace with upper case variant 
}

可以将字符串作为字符数组循环,并使用

  • 实例化一个空白字符串
  • 设置一个循环来循环角色
  • 检查是否需要将角色更改为其他角色
  • 是:检查字符是否为大写或小写,根据结果,将适当的字母放入新字符串中
  • 否:只需将该字符放入新字符串中即可
  • 将原始字符串设置为新字符串
  • 可能不是最有效或最壮观的做事方式,但它很简单,而且很有效

    另一方面:我不确定你是如何转换字符的,但如果你说,将字符向下移动字母表(当你确实想转换它们时),以恒定的量,让我们假设你移动了3。所以a->d和E->G或者类似的东西,然后你可以从字符中获取ASCII值,添加3(如果你想转换它),然后从ASCII值中获取字符。如上所述。不过,您必须进行检查,以确保从字母表的末尾返回。(或者开始,如果您要向左换档)

    编辑#1:(将上面的内容保留在那里)

    非常大的代码块。。。很抱歉这是我所能看到的最好的方法来满足你的要求。希望有人能想出一个更优雅的方式。如果您需要澄清,请发表评论或其他任何意见

        // (to be clear) This is Elias' (original) code modified.
        static void Main(string[] args)
        {
            string input = "As he DIDN'T ACHIEVE Success, he was fired";
            Dictionary<string, string> map = new Dictionary<string, string>();
            map.Add("didn't achieve success", "failed miserably");
    
            string temp = input;
            foreach (var entry in map)
            {
                string key = entry.Key;
                string value = entry.Value;
                temp = Regex.Replace(temp, key, match =>
                {
                    string[] matchSplit = match.Value.Split(' ');
                    string[] valueSplit = value.Split(' ');
    
                    // Set the number of words to the lower one.
                    // If they're the same, it doesn't matter.
                    int numWords = (matchSplit.Length <= valueSplit.Length) 
                        ? matchSplit.Length
                        : valueSplit.Length;
    
                    // only first letter of first word capitalized
                    // only first letter of every word capitalized
                    // all letters capitalized
                    char[] result = value.ToCharArray(); ;
                    for (int i = 0; i < numWords; i++)
                    {
                        if (char.IsUpper(matchSplit[i][0]))
                        {
                            bool allIsUpper = true;
                            int c = 1;
                            while (allIsUpper && c < matchSplit[i].Length)
                            {
                                if (!char.IsUpper(matchSplit[i][c]) && char.IsLetter(matchSplit[i][c]))
                                {
                                    allIsUpper = false;
                                }
                                c++;
                            }
                            // if all the letters of the current word are true, allIsUpper will be true.
                            int arrayPosition = ArrayPosition(i, valueSplit);
                            Console.WriteLine(arrayPosition);
                            if (allIsUpper)
                            {
                                for (int j = 0; j < valueSplit[i].Length; j++)
                                {
                                    result[j + arrayPosition] = char.ToUpper(result[j + arrayPosition]);
                                }
                            }
                            else
                            {
                                // The first letter.
                                result[arrayPosition] = char.ToUpper(result[arrayPosition]);
                            }
                        }
                    }
    
                    return new string(result);
                }, RegexOptions.IgnoreCase);
            }
            Console.WriteLine(temp); 
        }
    
        public static int ArrayPosition(int i, string[] valueSplit)
        {
            if (i > 0)
            {
                return valueSplit[i-1].Length + 1 + ArrayPosition(i - 1, valueSplit);
            }
            else
            {
                return 0;
            }
    
            return 0;
        }
    
    /(需要澄清)这是Elias(原始)代码修改。
    静态void Main(字符串[]参数)
    {
    string input=“由于他没有取得成功,他被解雇了”;
    字典映射=新字典();
    添加(“没有取得成功”,“惨败”);
    字符串温度=输入;
    foreach(映射中的var条目)
    {
    string key=entry.key;
    字符串值=entry.value;
    temp=Regex.Replace(temp,key,match=>
    {
    字符串[]matchSplit=match.Value.Split(“”);
    字符串[]valueSplit=value.Split(“”);
    //将字数设置为较低的字数。
    //如果它们是一样的,那没关系。
    int numWords=(matchSplit.Length 0)
    {
    返回值拆分[i-1]。长度+1+数组位置(i-1,值拆分);
    }
    其他的
    {
    返回0;
    }
    返回0;
    }
    
    不确定这会有多好,但这就是我想到的:

            string input = "A bgt abc hyi. Abc Ab df h";
            Dictionary<string, string> map = new Dictionary<string, string>();
            map.Add("abc", "cde");
            map.Add("ab df", "de");
    
            string temp = input;
            foreach (var entry in map)
            {
                string key = entry.Key;
                string value = entry.Value;
                temp = Regex.Replace(temp, key, match =>
                {
                    bool isUpper = char.IsUpper(match.Value[0]);
    
                    char[] result = value.ToCharArray();
                    result[0] = isUpper
                        ? char.ToUpper(result[0])
                        : char.ToLower(result[0]);
                    return new string(result);
                }, RegexOptions.IgnoreCase);
            }
            label1.Text = temp; // output is A bgt cde hyi. Cde De h
    
    string input=“A bgt abc hyi.abc Ab df h”;
    字典映射=新字典();
    地图添加(“abc”、“cde”);
    添加地图(“ab df”、“de”);
    字符串温度=输入;
    foreach(映射中的var条目)
    {
    string key=entry.key;
    字符串值=entry.value;
    temp=Regex.Replace(temp,key,match=>
    {
    bool isUpper=char.isUpper(match.Value[0]);
    char[]result=value.ToCharArray();
    结果[0]=isUpper
    ?char.ToUpper(结果[0])
    :char.ToLower(结果[0]);
    返回新字符串(结果);
    },RegexOptions.IgnoreCase);
    }
    label1.Text=temp;//输出为bgt cde hyi.cde De h
    
    编辑 在阅读了修改后的问题之后,这里是我修改后的代码(结果是与@Sephallia的代码类似的步骤..和类似的变量名lol)

    现在的代码有点复杂,但我觉得没问题

            string input = 
            @"As he didn't achieve success, he was fired.
            As he DIDN'T ACHIEVE SUCCESS, he was fired.
            As he Didn't Achieve Success, he was fired.
            As he Didn't achieve success, he was fired.";
            Dictionary<string, string> map = new Dictionary<string, string>();
            map.Add("didn't achieve success", "failed miserably");
    
    
            string temp = input;
            foreach (var entry in map)
            {
                string key = entry.Key;
                string value = entry.Value;
                temp = Regex.Replace(temp, key, match =>
                {
                    bool isFirstUpper, isEachUpper, isAllUpper;
    
                    string sentence = match.Value;
                    char[] sentenceArray = sentence.ToCharArray();
    
                    string[] words = sentence.Split(' ');
    
                    isFirstUpper = char.IsUpper(sentenceArray[0]);
    
                    isEachUpper = words.All(w => char.IsUpper(w[0]) || !char.IsLetter(w[0]));
    
                    isAllUpper = sentenceArray.All(c => char.IsUpper(c) || !char.IsLetter(c));
    
                    if (isAllUpper)
                        return value.ToUpper();
    
                    if (isEachUpper)
                    {
                        // capitalize first of each word... use regex again :P
                        string capitalized = Regex.Replace(value, @"\b\w", charMatch => charMatch.Value.ToUpper());
                        return capitalized;
                    }
    
    
                    char[] result = value.ToCharArray();
                    result[0] = isFirstUpper
                        ? char.ToUpper(result[0])
                        : char.ToLower(result[0]);
                    return new string(result);
                }, RegexOptions.IgnoreCase);
            }
            textBox1.Text = temp; 
            /* output is :
            As he failed miserably, he was fired.
            As he FAILED MISERABLY, he was fired.
            As he Failed Miserably, he was fired.
            As he Failed miserably, he was fired.
            */
    
    字符串输入=
    @“由于他没有取得成功,他被解雇了。
    由于没有取得成功,他被解雇了。
    由于没有取得成功,他被解雇了。
    由于他没有取得成功,他被解雇了。”;
    字典映射=新字典();
    添加(“没有取得成功”,“惨败”);
    字符串温度=输入;
    foreach(映射中的var条目)
    {
    string key=entry.key;
    字符串值=entry.value;
    temp=Regex.Replace(temp,key,match=>
    {
    布尔是第一上,伊萨克是上,伊索尔是上;
    字符串语句=match.Value;
    
    static string ReplaceCaseInsensitive(string Text, string Find, string Replace)
    {
        char[] NewText = Text.ToCharArray();
        int ReplaceLength = Math.Min(Find.Length, Replace.Length);
    
        int LastIndex = -1;
        while (true)
        {
            LastIndex = Text.IndexOf(Find, LastIndex + 1, StringComparison.CurrentCultureIgnoreCase);
    
            if (LastIndex == -1)
            {
                break;
            }
            else
            {
                for (int i = 0; i < ReplaceLength; i++)
                {
                    if (char.IsUpper(Text[i + LastIndex])) 
                        NewText[i + LastIndex] = char.ToUpper(Replace[i]);
                    else
                        NewText[i + LastIndex] = char.ToLower(Replace[i]);
                }
            }
        }
    
        return new string(NewText);
    }