【问题标题】:Substring the first occurrence of each part of a string in another string in c#在c#中的另一个字符串中将字符串的每个部分的第一次出现子串化
【发布时间】:2019-11-25 08:12:38
【问题描述】:

我有这两个字符串:

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

我想修剪字符串 2 中字符串 1 的第一次出现(从2 中的第一个索引开始),所以想要的结果是:

"DataSets.Project.Repositories.Entity"

最好的方法是什么?

【问题讨论】:

  • 两个字符串总是以相同的东西开头吗?到目前为止,您尝试过什么?
  • 您的字符串 1 没有出现在您的字符串 2 中...我认为您的意思是您要修剪包含在字符串 1 中的部分...
  • @AhmedAbdelhameed 不总是,我尝试对第一部分进行标记(用'.'分割)我会在它工作时添加我编写的代码。我的目标是最佳实践
  • @ZoharPeled 是的,我想在 2 中修剪部分 str1
  • @AliKleit 在您的问题中,您应该包含 不起作用 的代码。如果你设法让它工作,那就是答案。

标签: c# substring


【解决方案1】:

不清楚您所说的“最佳方式”是什么意思;如果你想通过. Split 每个字符串并摆脱 common chunks,即

  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);

【讨论】:

  • 谢谢!很好的解释
【解决方案2】:

不只是开头部分

如果只有第一部分很重要,为什么不简单地迭代直到第一个字符不匹配?

更新了我的答案,将@Dmitry Bychenko cmets 考虑在内。

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));

【讨论】:

  • 它会抛出一个异常'索引超出了数组的范围。'如果第二个字符串部分匹配第一个字符串 (str2 = "P")
猜你喜欢
  • 1970-01-01
  • 2010-12-12
  • 2011-12-19
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多