如何在 C# 中使用 String.Split 分隔字符串

一直以为split是用来分隔字符的,没想到还可以分隔数组。让程序变得更简单。微软官网的介绍在此记录下。

https://learn.microsoft.com/zh-cn/dotnet/csharp/how-to/parse-strings-using-split

 

1、分单个字符

1
2
3
4
5
6
7
string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ');
 
foreach (var word in words)
{
    System.Console.WriteLine($"<{word}>");
}

 2、String.Split 可使用多个分隔符。

1
2
3
4
5
6
7
8
9
10
11
12
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
 
string text = "one\ttwo three:four,five six seven";
System.Console.WriteLine($"Original text: '{text}'");
 
string[] words = text.Split(delimiterChars);
System.Console.WriteLine($"{words.Length} words in text:");
 
foreach (var word in words)
{
    System.Console.WriteLine($"<{word}>");
}

  3、String.Split 可采用字符串数组(充当用于分析目标字符串的分隔符的字符序列,而非单个字符)

1
2
3
4
5
6
7
8
9
10
11
12
string[] separatingStrings = { "<<", "..." };
 
string text = "one<<two......three<four";
System.Console.WriteLine($"Original text: '{text}'");
 
string[] words = text.Split(separatingStrings, System.StringSplitOptions.RemoveEmptyEntries);
System.Console.WriteLine($"{words.Length} substrings in text:");
 
foreach (var word in words)
{
    System.Console.WriteLine(word);
}

  

posted @   yinghualeihenmei  阅读(127)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2023-04-26 当前不会命中断点,还没有为该文档加载任何符号
2023-04-26 C# 获取上个月第一天和最后一天日期的方法;获取当前日期时间,当月第一天 或者当月最后一天;时间的格式方法
2023-04-26 Aspose.Cells简介及用到的几个方法
点击右上角即可分享
微信分享提示