簡體   English   中英

在C#中的另一個字符串中將字符串的每個部分的第一個匹配項子字符串化

[英]Substring the first occurrence of each part of a string in another string in c#

我有以下兩個字符串:

  1. "Project.Repositories.Methods"
  2. "Project.Repositories.DataSets.Project.Repositories.Entity"

我想修剪字符串2中字符串1的部分第一次出現(從2的第一個索引開始),因此所需的結果將是:

"DataSets.Project.Repositories.Entity"

最好的方法是什么?

您不清楚“最佳方式”是什么意思; 如果要用Split每個字符串. 並擺脫常見的塊 ,即

  Project        Project       - these chunks should be 
  Repositories   Repositories  - removed (they are same in both strings)
  Methods        DataSets
                 Project
                 Repositories
                 Entity 

您可以嘗試使用Linq,例如

  using System.Linq;

  ...

  string prefix = "Project.Repositories.Methods";
  string source = "Project.Repositories.DataSets.Project.Repositories.Entity";

  string[] prefixes = prefix.Split('.');

  string result = string.Join(".", source
    .Split('.')                                            // split into 
    .Select((value, index) => new { value, index})         // chunks  
    .SkipWhile(item => item.index < prefixes.Length &&     // skip
                       prefixes[item.index] == item.value) // common chunks
    .Select(item => item.value));

  Console.Write(result);

結果:

  DataSets.Project.Repositories.Entity

編輯:沒有Linq解決方案,受urbanSoft的答案啟發:

  string prefix = "Project.Repositories.Methods";
  string source = "Project.Repositories.DataSets.Project.Repositories.Entity";

  // We have 2 cases when all starting characters are equal:
  string result = prefix.Length >= source.Length 
    ? ""
    : source.Substring(source.IndexOf('.', prefix.Length) + 1);

  for (int i = 0, dotPosition = -1; i < Math.Min(prefix.Length, source.Length); ++i) {
    if (prefix[i] != source[i]) {
      result = source.Substring(dotPosition + 1);

      break;
    }
    else if (prefix[i] == '.')
      dotPosition = i;
  }

  Console.Write(result);

通過簡單的循環,它是很直接的:
將兩個字符串分割后. ,我們將在第二個字符串上循環,因為我們希望從中不包含matchinig元素。

string inputA = "Project.Repositories.Methods";
string inputB = "Project.Repositories.DataSets.Project.Repositories.Entity";

var partsA = inputA.Split('.').ToList();
var partsB = inputB.Split('.').ToList();

var results = new List<string>();
var lenghtB = partsB.Count();
var lenghtA = partsA.Count();

for (var i = 0; i < lenghtB ; i++)
{
    if ( i < lenghtA
         && partsA[i] == partsB[i])
    {
        continue;
    }
    results.Add(partsB[i]);
}

Console.WriteLine(string.Join(".", results));

現場演示

不只是第一部分

如果僅第一部分很重要,為什么不簡單地迭代直到第一個字符不匹配呢?

更新了我的答案,以考慮@Dmitry Bychenko的評論。

string a = "Project.Repositories.Data";
string b = "Project.Repositories.DataSets.Project.Repositories.Entity";
int dotIdx = 0;
for (int i = 0; i < a.Length; i++)
    if (a[i] != b[i])
        break;
    else
        dotIdx = a[i] == '.' ? (i+1) : dotIdx;
Console.WriteLine(b.Substring(dotIdx));

暫無
暫無

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

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