简体   繁体   中英

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

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

I loop through the whole string with a for loop, but I can't think of the sequence right now.

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". If you want to start capitalizing elsewhere, just change the initial value of 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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