1、假设有一个字符串strFilename=@"D:\C#程序设计\实验3\MyFile.TXT"。请使用字符串方法,取出路径中的文件名“MyFile.TXT”。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string strFileName = @"D:\C#程序设计\实验3设\MyFile.TXT";
string str1 = getFilename1(strFileName);
string str2 = getFilename1(strFileName);
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadKey();
}
public static string getFilename1(string strFilename)
{
char[] ch = strFilename.ToCharArray();
int n = strFilename.IndexOf("M");
string s = "";
for (int i = n; i < ch.Length; i++)
{
s += ch[i];
}
return s;
}
public static string getFilename2(string strFilename)
{
int n = strFilename.IndexOf('M');
return strFilename.Substring(n, strFilename.Length);
}
}
}
还有一个IndexOf(string str)方法,用法同IndexOf(string str),只是它的意思是返回str在字符串中最后一次出现的位置。
2、定义一个静态成员方法,该方法实现字符串翻转。如Reconvert("6221982")返回值为2891226。
代码:
</pre><pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = Console.ReadLine();
string str = Reverse(s);
Console.WriteLine(str);
Console.ReadKey();
}
public 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;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Hashtable hst = new Hashtable();
string[] no_name;
for (int j = 0; j < 5; j++)
{
no_name = Console.ReadLine().Split(' ');
int no = int.Parse(no_name[0]);
if (!hst.ContainsValue(no))
{
hst.Add(no_name[1],no);
}
else
{
Console.WriteLine("该学号已存在!");
}
}
foreach (DictionaryEntry item in hst)
{
int n = (int)item.Value;
if (n% 2 == 1)
Console.WriteLine("{0} {1}", item.Value,item.Key);
}
Console.ReadKey();
}
}
}