1,假设有一个字符串strFileName=@"D:\C#程序设计\实验3\MyFile.TXT".使用字符串方法,取出路径中的文件名"MyFile.TXT".(要求至少想出三种方法实现)。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program0
{
class Program
{
static void Main(string[] args)
{
string strFileName = "@\"D:\\C#程序设计\\实验3\\MyFile.TXT\"";
Console.WriteLine(getFileName1(strFileName));
Console.WriteLine(getFileName2(strFileName));
Console.WriteLine(getFileName3(strFileName));
Console.ReadKey();
}
private static string getFileName1(string str)
{
char[] c = str.ToCharArray();
int num1 = str.IndexOf('M');
string s="";
for (; num1 < str.Length - 1; num1++)
{
s+=c[num1]+"";
}
return s;
}
private static string getFileName2(string str)
{
int num2 = str.IndexOf("MyFile.TXT");
return str.Substring(num2, 10);
}
private static string getFileName3(string str)
{
int num3 = str.LastIndexOf("MyFile.TXT");
return str.Substring(num3, 10);
}
}
}
运行结果:
2.实验StringBuilder类。定义一个静态成员方法,该方法实现字符串反转。如Reconvert("6221982")返回值为2891226.自行设计程序验证上述方法正确性。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program0
{
class Program
{
static void Main(string[] args)
{
string str = "6221982";
Console.WriteLine(Reverse(str));
Console.ReadKey();
}
private static string Reverse(string str)
{
StringBuilder strReverse = new StringBuilder();
char[] c = str.ToCharArray();
for (int i = c.Length - 1; i >= 0; i--)
{
strReverse.Append(c[i]);
}
return strReverse.ToString();
}
}
}
运行结果:
3.输入学号和姓名,对不存在的学号加到hashtable类的实例中,对存在学号给出提示,结束输入后,输出学号为奇数的所有学生。
代码如下:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace Program0
{
class Program
{
static void Main(string[] args)
{
Hashtable hsTable1 = new Hashtable();
for (int i = 0; i <= 5; i++)
{
string[] str = Console.ReadLine().Split(' ');
int num = int.Parse(str[1]);
if (hsTable1.ContainsValue(num))
{
Console.WriteLine("该学号已被占用!");
}
else
{
hsTable1.Add(str[0], num);
}
}
Console.WriteLine("输出学号为奇数的:");
foreach (DictionaryEntry item in hsTable1)
{
int n = (int)item.Value;
if (n % 2 == 1)
Console.WriteLine("{0},{1}", item.Key, item.Value);
}
Console.ReadKey();
}
}
}
运行结果:
4.输入某人出生日期(以字符串方式输入,如1987-4-1)使用DateTime和TimeSpan类
(1)计算此人的年龄
(2)计算从现在到其60周岁期间,总共多少天。
代码如下:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace Program0
{
class Program
{
static void Main(string[] args)
{
string[] s = Console.ReadLine().Split('-');
int a = int.Parse(s[0]);
int b = int.Parse(s[1]);
int c = int.Parse(s[2]);
DateTime dt1 = new DateTime(a, b, c);
int age = DateTime.Now.Year - dt1.Year;
Console.WriteLine("此人的年龄为{0}", age);
a = a + 60;
DateTime dt2 = new DateTime(a, b, c);
TimeSpan ts = dt2 - DateTime.Now;
Console.WriteLine("从现在起到其60周岁期间,总共{0,5:F0}天", ts.TotalDays);
Console.ReadKey();
}
}
}
运行结果: