用大写字母替换中间字母

时间:2019-12-28 21:19:46

标签: c# string

有以下代码,它具有一个功能,该功能可以找到单词中间的字母(1个或2个字符)并将其大写,然后输出。

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(test("Rofl"));
        Console.WriteLine(test("Camel"));
        Console.WriteLine(test("R"));
    }

    public static String test(string value) {
        return value.Length % 2 == 0 
            ? value.Substring(value.Length / 2 - 1, 2).ToUpper()
            : value.Substring(value.Length / 2, 1).ToUpper();
    }
}

请告诉我,如何使该词完全衍生,但中间的字母完全由大写字母代替?

必须这样:

ROFl
CaMel
R

3 个答案:

答案 0 :(得分:3)

像这样? 不是最干净的方法。

public static string test(string value)
{
    if(string.IsNullOrEmpty(value)) return value;
    var array = value.ToCharArray();
    if (value.Length % 2 == 0)
    {
        array[value.Length / 2 - 1] = Char.ToUpper(array[value.Length / 2 - 1]);
        array[value.Length / 2] = Char.ToUpper(array[value.Length / 2]);
    }
    else
    {
        array[value.Length / 2] = Char.ToUpper(value[value.Length / 2]);
    }
    return new string(array);
}

答案 1 :(得分:1)

您可以使用对元素索引对有效的LINQ select AdID, DateRun, Metric, avg(Metric) over( partition by Metric, date_trunc(DateRun, month) ) month_avg_metric, Metric - avg(Metric) over( partition by Metric, date_trunc(DateRun, month) ) diff_with_month_avg_metric from mytable 重载来进行转换。

Select

这是相当不错的表现,因为public string MiddleLettersToUpper(string s) { IEnumerable<char> transformed; if (s.Length % 2 == 0) { transformed = s.Select((c, i) => i == s.Length / 2 || i == s.Length / 2 - 1 ? char.ToUpper(c) : c); } else { transformed = s.Select((c, i) => i == s.Length / 2 ? char.ToUpper(c) : c); } return string.Concat(transformed); } 在下面使用了string.Concat,因此您只需要对字符串进行一次遍历,并为结果分配一个字符串。

免责声明:使用StringBuilder时,此代码不关心区域性,因此不适合生产(也没有参数验证,但这很明显)。

答案 2 :(得分:0)

您可以使用正则表达式来做到这一点:

    public static string test(string value)
    {
        value = value ?? string.Empty;
        int half = value.Length % 2 == 0 ? (value.Length / 2) - 1: (value.Length / 2);
        Regex r = new Regex("(?<=^.{"+ half + "})[a-zA-Z]{1,2}(?=.{"+ half + "}$)");
        var match = r.Match(value);
        if (match != null)
        {
            var result = r.Replace(value, match.ToString().ToUpper());
            return result;
        }
        return value;
    }

首先,我们发现字母的一半计数(大写字母的字母数和末尾不增加字母的字母数)

正则表达式说明:

找到行的开头(^)+任何字符(。)的一半计数({half}),但不要接受它们(正数在Lookahead之前?<=)

然后在abc([a-zA-Z])中找到一个或两个字符({1,2})-这就是匹配项

,最后找到任何半角({half})+行尾($)的字符(。),但不要再使用它们(正向Lookahead?=后面)。

您可以在这里测试此正则表达式:regex101

相关问题