簡體   English   中英

如何在C#中創建分隔符並獲取值

[英]How to make a delimiter in c# and take the value

C#Visual Studio 17

假設我有一個值[3-4 + 6 * 2]甚至[3-4 + 20-0.5]的字符串,並且希望它們存儲在字符串數組中...研究發現,使用分割,修剪開始,修剪結束我們可以將它們分開...

.TrimStart('[')
.TrimEnd(']')
.Split('-','*','+');

但是我無法找到我們是否可以做到這一點

但是我也找不到任何地方如何存儲定界符,而是讓它們完成工作(我的意思是分隔)!

存儲的值將是{3,4,6,2},但是我想要這個{3,-,4,+,6,*,2},我該如何處理非凡的零!

通常 ,您必須使用解析器 如果只想分割並保留定界符,請查看Regex.Split

  string source = "[-3*4+20-0.5/-4.1]";

  //TODO: specify the delimiters:
  // If you want more delimiters, e.g. (, ), [, ] etc. 
  // for, say, 9*[(456+789)/(95-2.96)-3]
  // just add them into the array
  char[] delimiters = new char[]  { '*', '+', '-', '/' };

  string pattern = "(" + string.Join("|", delimiters
    .Select(item => Regex.Escape(item.ToString()))) + ")";

  string[] result = Regex
    .Split(source.TrimStart('[').TrimEnd(']'), pattern) // (...) preserves delim
    .Select(item => item.Trim()) // <- if you want to trim each item 
    .Where(item => !string.IsNullOrEmpty(item))
    .ToArray();

  // -, 3, *, 4, +, 20, -, 0.5, /, -, 4.1
  Console.Write(string.Join(", ", result));

編輯 :對於大文本,您可能需要手動實施拆分:

public static List<string> SplitPreserveSeparators(string source, char[] delimiters) {
  if (null == source)
    throw new ArgumentNullException("source") 
  else if (delimiters == null)
    throw new ArgumentNullException("delimiters") 

  int start = 0;
  int index = -1;

  List<string> items = new List<string>();

  while ((index = source.IndexOfAny(delimiters, start)) >= 0) {
    string value = source.Substring(start, index - start);

    if (!string.IsNullOrEmpty(value))
      items.Add(value);

    items.Add(source.Substring(index, 1));
    start = index + 1;
  }

  if (start < source.Length)
    items.Add(source.Substring(start));

  return items;
}

並使用它

string source = "[-3-4+20-0.5/-4.1]";
char[] delimiters = new char[]  { '*', '+', '-', '/' };

List<string> result =  SplitPreserveSeparators(
  source.TrimStart('[').TrimEnd(']'),
  delimiters);

Console.Write(string.Join(", ", result));

您可以實現一個簡單的自定義擴展方法,以使用存儲的分隔符進行拆分:

public static class StringExtensions
{
    public static string[] SplitStoreSeparators(this string input, char[] separators) 
    {
        List<string> tokens = new List<string>();

        StringBuilder sb = new StringBuilder(); 
        foreach (var c in input)
        {
            if (separators.Contains(c)) {
                if (sb.Length > 0) {
                    tokens.Add(sb.ToString());
                    sb.Clear();
                }
                tokens.Add(c.ToString());
            } else {
                sb.Append(c);
            }
        }

        if (sb.Length > 0)
            tokens.Add(sb.ToString());

        return tokens.ToArray();
    }
}

用法:

string input = Console.ReadLine().TrimStart('[').TrimEnd(']');
string[] output = input.SplitStoreSeparators(new[] { '+', '-', '/', '*' });

也許,枚舉此字符串並將每個元素存儲在結果數組中,跳過第一個和最后一個元素將得到所需的結果。

字符串是字符數組。 這樣,您可以使用String.ToCharArray()方法將其存儲為數組。 要刪除第一個和最后一個字符,我們可以通過在int為開始索引,以及int為所需的長度。

例如:

string myString = "[3-4+6*2]";

char[] myArray = myString.ToCharArray(1, myString.Length-2);

這將刪除字符串的第一個和最后一個字符,並將其余每個字符存儲在數組中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM