我遇到了以下问题:
我想将一部分字符串放入数组中。到目前为止没问题(splitstring),
但是,我不能使用splitstring
因为它需要我的操作员。
解释一个例子:
以下字符串:"47-62*5141"
我需要这样:{"47", "-", "62", "*", "5141"}
如果你能给我一个代码示例,我会很高兴的!
答案 0 :(得分:2)
答案 1 :(得分:0)
我做了一些丑陋的代码。但它确实有效。
class Program
{
static void Main(string[] args)
{
var text = "47-62**5141";
var splittedText = text.SplitAndKeepSeparator('-', '*');
foreach (var part in splittedText)
{
Console.WriteLine(part);
}
Console.ReadLine();
}
}
public static class StringExtensions
{
public static IEnumerable<string> SplitAndKeepSeparator(this string s, params char[] seperators)
{
var parts = s.Split(seperators, StringSplitOptions.None);
var partIndex = 0;
var isPart = true;
var indexInText = 0;
while (partIndex < parts.Length)
{
if (isPart)
{
var partToReturn = parts[partIndex];
if (string.IsNullOrEmpty(partToReturn))
{
partToReturn = s[indexInText].ToString();
}
else
{
isPart = false;
}
indexInText += partToReturn.Length;
partIndex++;
yield return partToReturn;
}
else
{
var currentSeparator = s[indexInText];
indexInText++;
isPart = true;
yield return currentSeparator.ToString();
}
}
}
答案 2 :(得分:0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] parts = new string[100];
var text = "47-62*5141";
int i = 0;
var splittedText = text.SplitAndKeepSeparator('-', '*', '+', '/');
foreach (var part in splittedText)
{
parts[i] = part;
i++;
}
Console.ReadLine();
Console.WriteLine(parts[0]);
Console.WriteLine(parts[1]);
Console.WriteLine(parts[2]);
Console.WriteLine(parts[3]);
Console.ReadLine();
}
}
}
public static class StringExtensions
{
public static IEnumerable<string> SplitAndKeepSeparator(this string s, params char[] seperators)
{
var parts = s.Split(seperators, StringSplitOptions.None);
var partIndex = 0;
var isPart = true;
var indexInText = 0;
while (partIndex < parts.Length)
{
if (isPart)
{
var partToReturn = parts[partIndex];
if (string.IsNullOrEmpty(partToReturn))
{
partToReturn = s[indexInText].ToString();
}
else
{
isPart = false;
}
indexInText += partToReturn.Length;
partIndex++;
yield return partToReturn;
}
else
{
var currentSeparator = s[indexInText];
indexInText++;
isPart = true;
yield return currentSeparator.ToString();
}
}
}
}