C#实现拆分字符串的示例详解

 更新时间:2024年02月04日 10:45:39   作者:wenchm  
这篇文章主要为大家详细介绍了C#如何分别使用正则表达式Regex.Split方法和String.Split方法实现拆分字符串,有需要的小伙伴可以参考一下

使用正则表达式可以拆分指定的字符串。同样地,使用字符串对象的Split方法也可以实现此功能。使用字符串对象的Split方法可以根据用户选择的拆分条件,方便地将字符串对象拆分为多个字符串。

一、使用的方法

1.使用Split(String, String)方法

在由正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。

public static string[] Split (string input, string pattern);

参数

input    String 要拆分的字符串。

pattern    String 要匹配的正则表达式模式。

返回

String[] 字符串数组。

例外

ArgumentException 出现正则表达式分析错误。

ArgumentNullException input 或 pattern 为 null。

RegexMatchTimeoutException 发生超时。 有关超时的详细信息,请参阅“备注”部分。

// 用正则表达式拆分字符串为一个子字符串数组
using System.Text.RegularExpressions;
 
namespace _086_2
{
    public class Example
    {
        public static void Main()
        {
            string input = @"01-31-2024";
            string pattern = @"(-)|(/)";
 
            foreach (string result in Regex.Split(input, pattern))
            {
                Console.WriteLine("{0}", result);
            }
        }
    }
}
// 运行结果:
/*
01
-
31
-
2024
*/

2.使用String.Split 方法

String对象的Split(Char[])方法,根据指定的分隔字符将字符串拆分为子字符串。

public string[] Split (params char[]? separator);

参数

separator    Char[] 分隔字符的数组、不包含分隔符的空数组或 null。

返回

String[] 一个数组,其元素包含此实例中的子字符串,这些子字符串由 separator 中的一个或多个字符分隔。 有关详细信息,请参阅“备注”部分。

// 将空格字符和制表 \t 符作为分隔符
namespace _086_1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);
            string s = "Today\tI'm going to school";
            string[] subs = s.Split(' ', '\t');
 
            foreach (var sub in subs)
            {
                Console.WriteLine($"Substring: {sub}");
                //Console.WriteLine("Substring: {0}", sub);//等效语句
            }
        }
    }
}
// 运行结果:
/*
Substring: Today
Substring: I'm
Substring: going
Substring: to
Substring: school
 */

下面来分享源代码吧:

二、源代码

1.源码

// 使用Split(String, String)方法拆分字符串
// 使用String对象的Split(Char[])方法拆字符串。
using System.Text.RegularExpressions;
namespace _086
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Button? button2;
        private Button? button1;
        private TextBox? textBox2;
        private TextBox? textBox1;
        private Label? label2;
        private Label? label1;
 
        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(6, 23),
                Name = "label1",
                Size = new Size(68, 17),
                TabIndex = 0,
                Text = "源字符串:"
            };
            // 
            // label2
            // 
            label2 = new Label
            {
                AutoSize = true,
                Location = new Point(6, 48),
                Name = "label2",
                Size = new Size(68, 17),
                TabIndex = 1,
                Text = "子字符串:"
            };
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(72, 17),
                Name = "textBox1",
                Size = new Size(262, 23),
                TabIndex = 2
            };
            // 
            // textBox2
            // 
            textBox2 = new TextBox
            {
                Font = new Font("Microsoft YaHei UI", 7F),
                Location = new Point(72, 48),
                Multiline = true,
                Name = "textBox2",
                Size = new Size(181, 153),
                TabIndex = 3
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(259, 48),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 4,
                Text = "拆分1",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // button2
            // 
            button2 = new Button
            {
                Location = new Point(259, 74),
                Name = "button2",
                Size = new Size(75, 23),
                TabIndex = 5,
                Text = "拆分2",
                UseVisualStyleBackColor = true
            };
            button2.Click += Button2_Click;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(340, 207),
                TabIndex = 0,
                TabStop = false,
                Text = "拆分字符串"
            };
            groupBox1.Controls.Add(button2);
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(textBox2);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label2);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();
 
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(364, 231);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "使用正则表达式拆分字符串";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }
        /// <summary>
        /// 拆分1:使用正则表达式根据数字进行拆分
        /// 遍历拆分后的字符串集合
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            if (textBox1!.Text != "")
            {
                textBox2!.Text = "";
                string[] str = MyRegex().Split(textBox1!.Text);
                foreach (string s in str)
                {
                    textBox2!.Text += s + Environment.NewLine;
                }
            }
            else
            {
                MessageBox.Show("源字符串不能为空", "拆分1");
            }
        }
        /// <summary>
        /// 拆分2
        /// </summary>
        private void Button2_Click(object? sender, EventArgs e)
        {
            if(textBox1!.Text != "")
            {
                textBox2!.Text = "";
                string s = textBox1!.Text;
                char[] separators = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
 
                string[] subs = s.Split(separators/*, StringSplitOptions.RemoveEmptyEntries*/);//注释后与正则方法输出相同结果
 
                foreach (var sub in subs)
                {
                    textBox2!.Text += sub + Environment.NewLine;
                }
            }
            else
            {
                MessageBox.Show("源字符串不能为空", "拆分2");
            }
        }
 
        [GeneratedRegex("[1-9]")]
        private static partial Regex MyRegex();
    }
}

2.生成效果

到此这篇关于C#实现拆分字符串的示例详解的文章就介绍到这了,更多相关C#拆分字符串内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 详解C#中的字符串拼接@ $

    详解C#中的字符串拼接@ $

    这篇文章主要介绍了C#中的字符串拼接@,$的相关知识,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-09-09
  • 如何在c#中使用Zlib压缩与解压

    如何在c#中使用Zlib压缩与解压

    这篇文章主要介绍了如何在c#中使用Zlib压缩与解压,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
    2021-04-04
  • 那些年,我还在学习C# 学习笔记续

    那些年,我还在学习C# 学习笔记续

    那些年学习C#,就是对C#相关的一些知识有一个了解,等到要用时才不会找不到方向,比如说扩展方法,开始时怎么觉得没有用,后来了解到asp.net MVC,它可以用来扩展Html类,比如做一个分页的方法;所以对一门语言了解宽一些是没有坏处的
    2012-03-03
  • C#连接Informix数据库的问题

    C#连接Informix数据库的问题

    这篇文章主要介绍了C#连接Informix数据库的问题,本文给大家介绍的非常详细,对大家的工作或学习具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-03-03
  • .net与javascript脚本的交互方法总结

    .net与javascript脚本的交互方法总结

    这篇文章主要介绍了.net与javascript脚本的交互方法,实例讲述了.net访问javascript的方法与javascript访问.net的方法,非常具有实用价值,需要的朋友可以参考下
    2014-10-10
  • C#路径,文件,目录及IO常见操作汇总

    C#路径,文件,目录及IO常见操作汇总

    这篇文章主要介绍了C#路径,文件,目录及IO常见操作,较为详细的分析并汇总了C#关于路径,文件,目录及IO常见操作,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-09-09
  • C#操作DataGridView获取或设置当前单元格的内容

    C#操作DataGridView获取或设置当前单元格的内容

    这篇文章介绍了C#操作DataGridView获取或设置当前单元格的内容,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-02-02
  • C#中分部方法和分部类分析

    C#中分部方法和分部类分析

    这篇文章主要介绍了C#中分部方法和分部类基本用法,并且较为详细的分析了分部方法和分部类使用时的注意事项,需要的朋友可以参考下
    2014-11-11
  • C#异步编程由浅入深(三)之详解Awaiter

    C#异步编程由浅入深(三)之详解Awaiter

    这篇文章主要介绍了C#异步编程由浅入深(三)之详解Awaiter,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • WPF实现绘制统计图(柱状图)的方法详解

    WPF实现绘制统计图(柱状图)的方法详解

    这篇文章主要为大家详细介绍了如何基于WPF实现实现统计图(柱状图)的绘制,文中的示例代码简洁易懂,对我们学习WPF有一定帮助,感兴趣的可以了解一下
    2022-07-07

最新评论