Skip to content
On this page

练习

在本挑战中,你将使用在本模块学到的技术。你的目标是改进一些格式不佳和注释不佳的代码,提高其可读性。

在 .NET 编辑器中从以下不可读代码开始

csharp
string str = "The quick brown fox jumps over the lazy dog.";
// convert the message into a char array
char[] charMessage = str.ToCharArray();
// Reverse the chars
Array.Reverse(charMessage);
int x = 0;
// count the o's
foreach (char i in charMessage) { if (i == 'o') { x++; } }
// convert it back to a string
string new_message = new String(charMessage);
// print it out
Console.WriteLine(new_message);
Console.WriteLine($"'o' appears {x} times.");

此代码的更高级别用途是反转字符串并计算特定字符出现的次数。

此代码存在许多明显降低其可读性的问题。

修改代码以提高其可读性

使用你在本模块中学到的方法改进代码,提高其可读性。

在下一个单元中,我们将介绍你可以做出的各种改进。

代码

csharp
/* 反转字符串并计算特定字符出现的次数 */
string OriginMessage = "The quick brown fox jumps over the lazy dog.";
char[] message = OriginMessage.ToCharArray();
Array.Reverse(message);

int letterCount = 0;
foreach (char letter in message) {
  if (letter == 'o') {
    letterCount++;
  }
}
string newMessage = new String(message);
Console.WriteLine(newMessage);
Console.WriteLine($"'o' appears {letterCount} times.");

// .god yzal eht revo spmuj xof nworb kciuq ehT
// 'o' appears 4 times.

答案

csharp
/*
   This code reverses a message, counts the number of times
   a particular character appears, then prints the results
   to the console window.
 */

string originalMessage = "The quick brown fox jumps over the lazy dog.";

char[] message = originalMessage.ToCharArray();
Array.Reverse(message);

int letterCount = 0;

foreach (char letter in message)
{
    if (letter == 'o')
    {
        letterCount++;
    }
}

string newMessage = new String(message);

Console.WriteLine(newMessage);
Console.WriteLine($"'o' appears {letterCount} times.");