问题
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