您的位置:首页 > 编程语言 > C#

C#上机 第九周 任务1 用于提取文件名

2012-10-22 16:12 267 查看
/*
* 程序头部注释开始
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:用于提取文件名
* 作    者:薛广晨
* 完成日期:2012  年 10 月  22  日
* 版 本号:x1.0

* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述: 定义一个静态成员方法,该方法用于提取文件名。
*           比如,给定一个字符串“c:\program files\Maths\all.dat”,使用该方法即可获取文件名all.dat。
*           自行设计程序验证上述方法正确性。
public static string getFilename(string file)
{
//提示:主体中使用string类的indexof方法和substring方法
}

* 程序输出:
* 程序头部的注释结束
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String file = @"c:\program files\Maths\all.dat";
String str = getFilename(file);
Console.WriteLine("{0}的文件名是{1}", file, str);
Console.ReadKey();
}

//方法一
public static string getFilename(string file)
{
//提示:主体中使用string类的indexof方法和substring方法
int index = 0;
int num = 0;
while ((index = file.IndexOf(@"\", index)) != -1)
{
index += 1;
if (index != -1)
{
num = index;
}
}
return file.Substring(num);
}
//方式二
/*public static string getFilename(string file)
{
//提示:主体中使用string类的indexof方法和substring方法
int index = 0;
string str = file;
while ((index = str.IndexOf(@"\")) != -1)
{
str = str.Substring(index + 1);
}
return str;
}*/

}
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  任务 c# string file class c