標籤:包括 i++ har 例子 字元替換 替換 substr div int
給定一個字串,請你將字串重新編碼,將連續的字元替換成“連續出現的個數+字元”。比如字串AAAABCCDAA會被編碼成4A1B2C1D2A。
輸入描述:
每個測試輸入包含1個測試案例每個測試案例輸入只有一行字串,字串只包括大寫英文字母,長度不超過10000。
輸出描述:
輸出編碼後的字串
輸入例子:
AAAABCCDAA
輸出例子:
4A1B2C1D2A
牛客網頁運行代碼如下:
using System;public class Program{ public static void Main(){ string input = System.Console.ReadLine(); int inputLength = input.Length; int keyCount = 0; char keyValue; char[] c = new char[inputLength]; for (int i = 0; i < inputLength; i++) { c[i] = Convert.ToChar(input.Substring(i, 1)); } for (int i = 0; i < inputLength; ) { keyValue = c[i]; while (i != inputLength && keyValue == c[i]) { i++; keyCount++; } Console.Write("{0}{1}", keyCount, keyValue); keyCount = 0; } Console.ReadKey(); }}
VS中的代碼如下:
using System;namespace 字串編碼{ class Program { static void Main(string[] args) { string input = System.Console.ReadLine(); int inputLength = input.Length; int keyCount = 0; char keyValue; char[] c = new char[inputLength]; for (int i = 0; i < inputLength; i++) { c[i] = Convert.ToChar(input.Substring(i, 1)); } for (int i = 0; i < inputLength; ) { keyValue = c[i]; while (i != inputLength && keyValue == c[i]) { i++; keyCount++; } Console.Write("{0}{1}", keyCount, keyValue); keyCount = 0; } Console.ReadKey(); } }}
歡迎交流。
字串編碼C#