我该如何拆分字符串

本文关键字:拆分 字符串 何拆分 | 更新日期: 2023-09-27 18:19:52

我有一些字符串要拆分。每个字符串构建如下:1月(10)安娜(100)等等…所以是一个名字,后面是一个空格,最后是一个括号之间的数字。我想把这个分成两串。字符串1只能是名称,字符串2只能是数字。有人知道怎么做吗?

我该如何拆分字符串

使用split方法并发送要由它们分割的字符数组。

string input = "Jan (10) Anna (100)";
string[] split = input.Split(new[] {' ', ')', '('}, StringSplitOptions.RemoveEmptyEntries);

这将为您提供阵列Jan , 10 , Anna , 100

正如您所看到的,甚至索引都是名称,之后的索引是它们的编号。所以穿这样的鞋吧。(注意,索引是基于0的,这意味着第一个索引是索引0。)

Tuple<string, string>[] pairs = new Tuple<string, string>[split.Length/2];
for (int i = 0; i < pairs.Length; i++)
{
    pairs[i] = new Tuple<string, string>(split[i * 2], split[(i * 2) + 1]); 
}

并像这样访问它们。

pairs[1].Item1 // will give you second person name
pairs[1].Item2 // will give you second person number

使用Regex

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "Jan (10) Anna (100)";
            string pattern = @"(?'word''w+)'s'((?'number''d+)')";
            MatchCollection matches = Regex.Matches(input,pattern);
            foreach(Match match in matches)
            {
                Console.WriteLine(match.Groups["word"].Value + " " + match.Groups["number"].Value);
            }
            Console.ReadLine();
        }
    }
}
​