零基础自学C#——Part7:IO操作、字符串API

上一部分介绍了哈希表/队列,堆栈/队列

这一部分来简单的学习和实操IO操作,补充一些常用的String API

一、简单的I/0操作

I:就是input 、O:就是output ,故称:输入输出流。将数据读入内存或者内存输出的过程

常见的IO流操作,一般说的是【内存】与【磁盘】之间的输入输出。

二、作用

持久化数据,保证数据不再丢失!

文件操作流程:打开文件、读写数据、关闭文件。

1:FileStream读写文件

位于命名空间:   System.IO,System.Text;

具体的各个部分见代码段

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

public class StringStreamTest : MonoBehaviour
{
    void Start()
    {
        CreateFile();
        ReadFile();
    }

    void Update()
    {
        
    }
    void CreateFile()
    {
        //定义文件路径

        string path= @"D:\UNITY3D\练习1\Project1\Assets/Resources/student.txt";
        
        //创建FileStream类的实例

        FileStream fileStream =new FileStream(path,FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);  
 //存储路径----存在则打开,不存在则创建----在Resources中创建了student.txt
       
        //定义学号
        string msg = "170026";

        //将字符串转为字节数组
        byte[] bytes =Encoding.UTF8.GetBytes(msg);

        //向文件中写入字节数组
        fileStream.Write(bytes,0,bytes.Length);

        //刷新缓冲区
        fileStream.Flush();

        //关闭流
        fileStream.Close();

    }

    void ReadFile()
    {
        //定义文件路径
        string path= @"D:\UNITY3D\练习1\Project1\Assets/Resources/student.txt";

        //判断是否含有指定文件,Exists指令
        if(File.Exists(path))
        {
            FileStream fileStream = new FileStream(path,FileMode.Open,FileAccess.Read);

            //定义存放文件信息的字节数组
            byte[] bytes = new byte[fileStream.Length];

            //读取文件信息
            fileStream.Read(bytes,0,bytes.Length);

            //将得到的字节型数组重写编码为字符型数组
            string c = Encoding.UTF8.GetString(bytes);
            Debug.Log("学生的学号为: ");

            //输出学生的学号

            Debug.Log(c);
            //关闭流

            fileStream.Close();
        }
        else
        {
            Debug.Log("您查找的文件不存在");
        }

    }
}

更多细节内容详见:

FileStream读写文件_阳光下的Smiles的博客-CSDN博客_filestream

2:StreamReader和 StreamWrite的使用

①:WriteFile代码实现

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class StreamTest : MonoBehaviour
{

    void Start()
    {
        WriteFile();
    }


    void Update()
    {
        
    }
    void WriteFile()
    {
        //定义文件路径
        string path= @"D:\UNITY3D\练习1\Project1\Assets/Resources/student2.txt";

        //创建StreamWrite类的实例
        StreamWriter streamWriter = new StreamWriter(path);

        //向文件中写入姓名
        streamWriter.WriteLine("小张");

        //向文件中写入手机号
        streamWriter.WriteLine("1244444");

        //刷新缓存
        streamWriter.Flush();
        //关闭流
        streamWriter.Close();

    }

详见:C# StreamWriter类:写入文件

②:ReadFile代码实现

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class StreamTest : MonoBehaviour
{

    void Start()
    {
        ReadFile();
    }

    void Update()
    {
        
    }

void ReadFile()
    {
        //定义文件路径
        string path= @"D:\UNITY3D\练习1\Project1\Assets/Resources/student2.txt";

        //创建StreamRead类的实例
        StreamReader streamReader =new StreamReader(path);

        //判断文件中是否有字符
        while(streamReader.Peek()!=-1)
        {
            //读取文件中的一行字符
            string str = streamReader.ReadLine();
            Debug.Log(str);
        }
        streamReader.Close();

    }
}

详见:C# StreamReader类:读取文件

3:Directory/DirectoryInfo  操作文件夹

①:Directory

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class DirectoryTest : MonoBehaviour
{

    void Start()
    {
        TestDirectory();
    }
 
    void Update()
    {
        
    }
    void TestDirectory()
    {
        string strDir =@"D:\UNITY3D\练习1\Project1\Assets\Resources\DirTest";   
        //定义位置的该文件夹
                                       

        if(Directory.Exists(strDir))                             //判断Dir是否存在

        {
            Directory.Delete(strDir);                            //删除指定文件夹
        }
        else
        {
        Directory.CreateDirectory(strDir);                           
                                            //通过调用CreateDirectory指令创建文件夹
        }
    
        Directory.Move(strDir,@"D:\UNITY3D\练习1\Project1\Assets\DirTest");    
                                                   //将DirTest文件夹移动到Assets

    
        //Directory.Delete(@"D:\UNITY3D\练习1\Project1\Assets\DirTest");         
                          //显示Dir有子文件夹,不可以直接删除,如果没有子文件夹会默认删除

        Directory.Delete(@"D:\UNITY3D\练习1\Project1\Assets\DirTest",true);   
                          //传入true,此时会删除目录下所有子文件夹,并删除目标文件夹

详见C# Directory类:文件夹操作

②:DirectoryInfo

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class DirectoryTest : MonoBehaviour
{

    void Start()
    {
        TestDirectoryInfo();
    }
 
    void Update()
    {
        
    }
void TestDirectoryInfo()
    {
        string strDir =@"D:\UNITY3D\练习1\Project1\Assets\Resources\DirTest";
        DirectoryInfo directoryInfo = new DirectoryInfo(strDir);
        directoryInfo.Create();
       
        directoryInfo.CreateSubdirectory("code-1");                      //创建子文件夹
        directoryInfo.CreateSubdirectory("code-2");
       
        //directoryInfo.Delete();                                        
                                                          //有子文件夹不可以删除

        //directoryInfo.Delete(true);                                    
                                                       //加true可以删除子文件夹


        IEnumerable<DirectoryInfo> dir= directoryInfo.EnumerateDirectories();
        foreach(var v in dir)
        {
            Debug.Log(v.Name);
        }

        directoryInfo.MoveTo(@"D:\UNITY3D\练习1\Project1\Assets\DirTest");   //将DirTest移动到了Assets下面

    }  
}

详见C# Directoryinfo类:文件夹操作

二、常用的String API

1:声明两个字符串

string str="VIPILETF";
string str2="vipsiltf";

2:Length属性

Debug.Log("str.Length"+str.Length);                        //输出为8,

3:Compare方法   返回值=0,则代表两个字符串相等,如果不为0,则不相等(在C#中,大小写是敏感的,除非true)

Debug.Log("string.Compare"+string.Compare(str,str2));              //输出为1,代表不相等

#3.1:与Compare方法等价,使用If else语句

if(str==str2)
        Debug.Log("str==str2");
        else
        Debug.Log("str!=str2");                                            //输出为str!=str2

#3.2:与Compare方法等价,使用Equla方法

 Debug.Log("string.Equlas"+string.Equals(str,str2));                    //输出为false

#3.3:Equals的另一种用法

Debug.Log("String.Equals"+str.Equals(str2));                           //输出为false

#3.4:加上true以后,不区分大小写,只要内容相等就判定为相等

 Debug.Log("string.Compare(ignore)"+string.Compare(str,str2,true));         //输出为0

4:Concat方法:实现字符串拼接(支持多个字符串的拼接)

Debug.Log("string.Concat"+string.Concat(str,str2));             //输出为VIPSKILLvipskill

#4.1:与Concat等方法等价,括号直接把两个字符串拼接

Debug.Log("str+str2"+(str+str2));

#4.2:Format拼接格式,name+{从0开始,下标},age:{顺序到1},后面加上0,1的内容

Debug.Log(string.Format("name:{0} age:{1}","张三",14));                      
//输出为name:张三,age:14

5:Contains方法:判断一个字符串是否存在目标字符串(不能判断字符)

Debug.Log("str.Contains(L)"+str.Contains("L"));                            //输出为true

Debug.Log("str.Contains(l)"+str.Contains("l"));                            //输出为false,单引号则为字符,不可用Contains

#5.1:与Contains类似的方法,IndexOf方法-" "字符串

Debug.Log("str.IndexOf(l)"+str.IndexOf("l"));                        //输出为-1,表示不存在

Debug.Log("str.IndexOf(L)"+str.IndexOf("L"));                         
//输出为6,数字表示该字符在字符串中第一次出现的位置

#5.2:与Contains类似的方法,IndexOf方法-''字符

Debug.Log("str.IndexOf(L)"+str.IndexOf('L'));                            
 //输出为6,数字表示该字符在字符串中第一次出现的位置

#5.3:与Contains类似的方法,IndexOf方法,寻找字符在当前string对象中最后一次出现的索引位置

Debug.Log("str.LastIndexOf(L)"+str.LastIndexOf('L'));                     
//输出为7,表示字符'L'最后一次出现的位置在第七位

#5.4:与Contains类似的方法,StartWiths方法,查看字符串开头是否为指定的字符串

Debug.Log("str.StartWiths(L)"+str.StartsWith("L"));                         
//输出为false,表示该字符串不是以L开头

Debug.Log("str.StartWiths(V)"+str.StartsWith("V"));                         
//输出为true,表示该字符串以V开头

#5.5:与Contains类似的方法,EndsWith方法,查看字符串结尾是否为指定的字符串

Debug.Log("str.EndsWith(L)"+str.EndsWith("L"));                              
//输出为true,表示该字符串是以L结尾

Debug.Log("str.EndsWith(V)"+str.EndsWith("V"));                              
//输出为true,表示该字符串不是以V结尾

6:Insert插入方法:返回一个新的字符串,其中,指定的字符串被插入在当前 string 对象的指定索引位置

Debug.Log("str.Insert(0,xxx)"+str.Insert(0,"xxx")+str);                           
//输出为xxxVIPSKILL,表示在0号位置插入了xxx字符串,但是对原来的字符串并没有影响

Debug.Log("str.Insert(3,xxx)"+str.Insert(3,"xxx"));                                         //输出为VIPxxxSKILL,3号表示在P后插入了xxx

7:static IsNullOrEmpty方法:指示指定的字符串是否为 null 或者是否为一个空的字符串。

Debug.Log("strIsNullOrEmpty:"+string.IsNullOrEmpty(str));                           
//输出为false,说明指定的字符串不是空的

//str="";
Debug.Log("strIsNullOrEmpty:"+string.IsNullOrEmpty(str));                           //true,说明str为空

8:Remove 移除方法:移除当前实例中的所有字符,从指定位置开始,一直到最后一个位置为止,并返回字符串。

Debug.Log("str.Remove(0,2):"+str.Remove(0,2)+str);                                      
//输出为PSKILL,删除了前两个字符

9:Replace替换方法:把当前 string 对象中,所有指定的字符替换为另一个指定的字符,并返回新的字符串。

Debug.Log("str.Replace(V,v):"+str.Replace("V","v"));                               

10:Split切割方法

string [] array=str.Split(new char[]{'P'});                            //切割针对的是字符
        for (int i = 0; i < array.Length; i++)
        {
            Debug.Log("str.Split(new char[]{P}),i:"+i+",Content:"+array[i]);      

        }

11:ToLower方法:将字符串中的字母改为小写;ToUpper方法:将字符串中的所有字母改为大写。

Debug.Log("str.ToLower:"+str.ToLower()+"str.ToUpper:"+str2.ToUpper());            
//str成了vipskill  ,str2成了VIPSKILL,大小写转换是针对所有字母,一般用在对资源名字进行处理的时候

12:Trim去掉空格方法:移除当前 String 对象中的所有前导空白字符和后置空白字符,TrimStart()只删除字符串的头部的空格。TrimEnd()只删除字符串尾部的空格。

string str3=" abc";
        Debug.Log("str3.Trim:"+str3.Trim());                                           
//输出为abc,没有前面的空格,值得注意的是,Trim指令只能够去除前面后后面的,而不能去除中间的
        Debug.Log("str3.TrimStart:"+str3.TrimStart());
        Debug.Log("str3.TrimEnd:"+str3.TrimEnd());

更多有关String API的详见:C# 字符串(String) | 菜鸟教程

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Laker404

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值