我有以下两个字符串:
"Project.Repositories.Methods"
"Project.Repositories.DataSets.Project.Repositories.Entity"
我想修剪字符串2中字符串1的部分第一次出现(从2
中的第一个索引开始),因此所需的结果将是:
"DataSets.Project.Repositories.Entity"
做到这一点的最佳方法是什么?
答案 0 :(得分:6)
目前尚不清楚您所说的“最佳方式”是什么意思;如果您想按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
编辑:否,基于 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);
答案 1 :(得分:0)
不仅仅是第一部分
如果只有第一部分很重要,为什么不简单地迭代直到第一个字符不匹配呢?
更新了我的答案,以考虑到@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));