简体   繁体   English

如何在 C# 中将字符串的每三个字母大写?

[英]How can I capitalize every third letter of a string in C#?

How can I capitalize every third letter of a string in C#?如何在 C# 中将字符串的每三个字母大写?

I loop through the whole string with a for loop, but I can't think of the sequence right now.我用for循环遍历整个字符串,但我现在想不出序列。

I suspect you just want something like this:我怀疑你只是想要这样的东西:

// String is immutable; copy to a char[] so we can modify that in-place
char[] chars = input.ToCharArray();
for (int i = 0; i < chars.Length; i += 3)
{
    chars[i] = char.ToUpper(chars[i]);
}
// Now construct a new String from the modified character array
string output = new string(chars);

That assumes you want to start capitalizing from the first letter, so "abcdefghij" would become "AbcDefGhiJ".假设您想从第一个字母开始大写,因此“abcdefghij”将变为“AbcDefGhiJ”。 If you want to start capitalizing elsewhere, just change the initial value of i .如果您想在其他地方开始大写,只需更改i的初始值。

        var s = "Lorem ipsum";
        var foo = new string(s
            .Select((c, i) => (i + 1) % 3 == 0 ? Char.ToUpper(c) : c)
            .ToArray());

You are already looping through the characters inside a string?您已经在遍历字符串中的字符了吗? Then add a counter, increment it on each iteration, and if it is 3, then use .ToUpper(currentCharacter) to make it upper case.然后添加一个计数器,在每次迭代时递增,如果是 3,则使用.ToUpper(currentCharacter)使其大写。 Then reset your counter.然后重置你的计数器。

You could just use a regular expression.您可以只使用正则表达式。

If the answer is every third char then you want如果答案是每三个字符那么你想要

var input = "sdkgjslgjsklvaswlet";
var regex = new Regex("(..)(.)");
var replacement = regex.Replace(input, delegate(Match m)
                     {
                         return m.Groups[1].Value + m.Groups[2].Value.ToUpper();
                     });

If you want every third character, but starting with the first you want:如果您想要每三个字符,但从您想要的第一个字符开始:

var input = "sdkgjslgjsklvaswlet";
var regex = new Regex("(.)(..)");
var replacement = regex.Replace(input, delegate(Match m)
                     {
                         return m.Groups[1].Value.ToUpper() + m.Groups[2].Value;
                     });

If you want a loop, you can convert to a character array first, so you can alter the values.如果需要循环,可以先转换为字符数组,以便更改值。

For every third character:每三个字符:

var x = input.ToCharArray();
for (var i = 2; i <x.Length; i+=3) {
    x[i] = char.ToUpper(x[i]);
}
var replacement = new string(x);

For every third character from the beginning:对于从头开始的每三个字符:

var x = input.ToCharArray();
for (var i = 0; i <x.Length; i+=3) {
    x[i] = char.ToUpper(x[i]);
}
var replacement = new string(x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM