Home > Software design >  How to format each character in input string according to it position?
How to format each character in input string according to it position?

Time:12-01

im noob at prog, so i need help.

Need to make a string from each word in the array so that each letter copies itself as many times as the serial number in the word it has, and each new character must starts with uppercase;

Example:

"abcd" -> "A-Bb-Ccc-Dddd"

"RqaEzty" -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"

"cwAt" -> "C-Ww-Aaa-Tttt"

One of ways I tried to do it:

public static String Accum(string s) 
  {
    string res;
     for(int i = 0; i < s.Length; i  )
       {
       res  = s[i].ToUpper()   s[i].ToLower().Repeat(i)   (i < s.Length - 1 ? "-": "");
     }
    return res;
  }

  • some errors, that I understand, but can't understand what to do with them(google didnt help so much):

error CS1501: No overload for method 'ToUpper' takes 0 arguments

error CS0165: Use of unassigned local variable 'res'

CodePudding user response:

Funny... I think I saw this on leetcode.com or codewars.com...

Anyway...

string  Accum(string s) 
{
    var sb = new StringBuilder(s.Length * s.Length); // a bit too long, but that's Ok
    for(int i=0; i < s.Length;   i)
    {
        sb.Append(Char.ToUpper(str[i]));
        sb.Append(s[i], i);    // i is repeat count.  Fortunately, it silently accepts 0 for count
        sb.Append('-');
    }
    
    // Trick to remove last character;
    sb.Length--;
    
    return sb.ToString();
}

As for the error you were getting:

error CS1501: No overload for method 'ToUpper' takes 0 arguments

ToUpper() works on string. s[i] is just a character.

error CS0165: Use of unassigned local variable 'res'

If s is an empty string, we never enter the loop, and res is unassigned.

CodePudding user response:

Simple oneline with :

string f(string s) => CultureInfo.CurrentCulture.TextInfo.ToTitleCase(String.Join("-", s.Select((x, i) => new string (Char.ToLower(x), i 1))));

online demo

  • Related