.NET实验6-3

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cd1202/article/details/51106380
 假设有一个字符串strFileName = @"D:\C#程序设计\实验3\MyFile.TXT"。请使用字符串方法,取出路径中的文件名"MyFile.TXT"。


      public static string getFilename(string strFileName)
  {


        //提示:主体中使用string类的indexof方法、lastindexof方法和substring等方法


  }

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

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string strFileName = @"D:\C#程序设计\实验3\MyFile.TXT";
            Console.WriteLine(getFilename(strFileName));
            Console.ReadKey();

        }
        public static string getFilename(string strFileName)
        {
            int x = strFileName.LastIndexOf("\\") + 1;//使用string类的lastindexof方法
            string str = strFileName.Substring(x);
            return str;
        }

    }
}

运行结果:


总结:

    这道题取文件名最简单的应该是运用lastindexof方法,从字符串的末尾开始检索,检索到需要字符时,返回字符位置。

猜你喜欢

转载自blog.csdn.net/cd1202/article/details/51106380
6-3