Skip to main content

3月31日 字符串练习题

根据你的课件内容,我设计了5道字符串遍历的练习题,涵盖 for 循环、foreach 循环、索引访问、字符判断等核心技能。每道题都包含明确的需求、示例输入输出以及参考代码,方便学生练习或教师布置作业。


题目1:逐个输出字符串中的字符

编写一个C#程序,从控制台输入一个字符串,然后使用 for 循环遍历该字符串,将每个字符逐行输出。
示例输入

Hello

示例输出

H
e
l
l
o
参考代码
using System;

class Program
{
static void Main()
{
Console.Write("请输入一个字符串:");
string input = Console.ReadLine();

for (int i = 0; i < input.Length; i++)
{
Console.WriteLine(input[i]);
}
}
}

题目2:统计指定字符出现的次数

编写一个C#程序,要求:

  1. 从控制台输入一个字符串。
  2. 再输入一个要查找的字符。
  3. 使用 foreach 循环遍历字符串,统计该字符在字符串中出现的次数(区分大小写),并输出结果。

示例输入

abracadabra
a

示例输出

字符 'a' 出现了 5 次。
参考代码
using System;

class Program
{
static void Main()
{
Console.Write("请输入字符串:");
string input = Console.ReadLine();

Console.Write("请输入要统计的字符:");
char target = Console.ReadLine()[0]; // 取第一个字符

int count = 0;
foreach (char c in input)
{
if (c == target)
{
count++;
}
}

Console.WriteLine($"字符 '{target}' 出现了 {count} 次。");
}
}

题目3:反转字符串

编写一个C#程序,输入一个字符串,然后通过遍历(使用 for 循环从后向前)将字符串反转,并输出反转后的结果。
要求:不能直接使用 Array.Reverse 等方法,必须通过手动遍历构建新字符串。

示例输入

hello

示例输出

olleh
参考代码
using System;

class Program
{
static void Main()
{
Console.Write("请输入字符串:");
string input = Console.ReadLine();

string reversed = "";
for (int i = input.Length - 1; i >= 0; i--)
{
reversed += input[i];
}

Console.WriteLine("反转后:" + reversed);
}
}

题目4:判断回文字符串

编写一个C#程序,输入一个字符串,判断它是否是回文(即正读反读都一样,忽略大小写)。
要求

  • 使用 for 循环遍历字符串的一半长度进行比较。
  • 比较时忽略大小写(可先将字符串转为小写或大写)。

示例输入1

level

示例输出1

是回文

示例输入2

Hello

示例输出2

不是回文
参考代码
using System;

class Program
{
static void Main()
{
Console.Write("请输入字符串:");
string input = Console.ReadLine();

string lowerInput = input.ToLower(); // 忽略大小写
bool isPalindrome = true;

for (int i = 0; i < lowerInput.Length / 2; i++)
{
if (lowerInput[i] != lowerInput[lowerInput.Length - 1 - i])
{
isPalindrome = false;
break;
}
}

if (isPalindrome)
Console.WriteLine("是回文");
else
Console.WriteLine("不是回文");
}
}

题目5:将字符串中的小写字母转换为大写

编写一个C#程序,输入一个字符串,遍历每个字符,如果是小写字母则转换为大写字母,其他字符保持不变,最后输出转换后的字符串。
提示:可以使用 char.IsLowerchar.ToUpper 方法。

示例输入

C# is Fun!

示例输出

C# IS FUN!
参考代码
using System;

class Program
{
static void Main()
{
Console.Write("请输入字符串:");
string input = Console.ReadLine();

string result = "";
foreach (char c in input)
{
if (char.IsLower(c))
{
result += char.ToUpper(c);
}
else
{
result += c;
}
}

Console.WriteLine("转换后:" + result);
}
}

这5道题覆盖了字符串遍历的常见模式,由浅入深,适合初学者巩固 forforeach 循环以及字符串索引的使用。如果需要更多变体(如统计字母个数、替换字符等),可在此基础上继续扩展。