Reputation: 3649
I have these two strings:
"Project.Repositories.Methods"
"Project.Repositories.DataSets.Project.Repositories.Entity"
I want to trim the first occurrence (from the first index in 2
) of parts of string 1 in string 2, so the desired result would be:
"DataSets.Project.Repositories.Entity"
What is the best way of doing this?
Upvotes: 1
Views: 209
Reputation: 186698
It's not clear what do you mean by "best way"; if you want to Split
each string by .
and get rid of common chunks, i.e.
Project Project - these chunks should be
Repositories Repositories - removed (they are same in both strings)
Methods DataSets
Project
Repositories
Entity
you can try using Linq e.g.
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);
Outcome:
DataSets.Project.Repositories.Entity
Edit: No Linq solution, inspired by urbanSoft's answer:
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);
Upvotes: 6
Reputation: 760
No just the first parts
If only the first parts do matter why not simply iterate until the first character mismatch?
Updated my answer to take @Dmitry Bychenko comments into account.
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));
Upvotes: 0