我有以下两个字符串:
"Project.Repositories.Methods""Project.Repositories.DataSets.Project.Repositories.Entity" 我想修剪2字符串2中字符串1的部分首次出现(从中的第一个索引开始),因此所需的结果将是:
"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
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用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);
Run Code Online (Sandbox Code Playgroud)
结果:
DataSets.Project.Repositories.Entity
Run Code Online (Sandbox Code Playgroud)
编辑:没有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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |