OJ Problem 3444 C#提取文件名

 

题目描述

假设有一个字符串包含了文件名、扩展名和路径,如strFileName=@“D:\C#程序设计\实验3\MyFile.TXT”。请使用C#编写一个静态方法,该方法能够取出路径中的文件名“MyFile.TXT”。

输入

一个包含了文件名,扩展名和路径的字符串。

输出

字符串中的文件名。

样例输入

strFileName=@“D:\C#程序设计\实验3\MyFile.TXT”

样例输出

MyFile.TXT

提示

提示:使用string类的lastindexof和substring等方法实现。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            //String.LastIndexOf 方法返回指定的 Unicode 字符或 String 在此实例中的最后一个匹配项的索引位置。
            int splitIndex1 = str.LastIndexOf("\\");
            int splitIndex2 = str.LastIndexOf("TXT");
            //String.Substring (Int32, Int32)从此实例检索子字符串。子字符串从指定的字符位置开始且具有指定的长度
            string txtName = str.Substring(splitIndex1 + 1,splitIndex2+2-splitIndex1);
            Console.WriteLine(txtName);
        }
    }
}

以下为某博客园截图,非原创,侵删

猜你喜欢

转载自blog.csdn.net/wangws_sb/article/details/104812465