How to capitalize every third letter ot a string in C#?

我们两清 提交于 2019-12-13 07:34:59

问题


does anybody know how to 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.

Thanks in advance


回答1:


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.




回答2:


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



回答3:


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.




回答4:


You could just use a regex

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 char 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 char array first so you can alter the values

For every third char:

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 char 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);


来源:https://stackoverflow.com/questions/22165453/how-to-capitalize-every-third-letter-ot-a-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!