user1108948
user1108948

Reputation:

Find prefixes and suffixes of a string

Say we have a string "bread", I want to get all prefixes and suffixes of the string. The definition of it as the image below.

prefixes:

b,br,bre,brea

suffixes:

read,ead,ad,d

string

Now I only can get the prefixes and I think it is wrong.

string pattern = "bread";
var prefixes = pattern.Where(x => x.ToString().StartsWith(pattern.Substring(0, 1))).ToList();

Upvotes: 0

Views: 8062

Answers (3)

Dirk
Dirk

Reputation: 10958

I would do it like this:

string pattern = "bread";
var prefixes = Enumerable.Range(1, pattern.Length - 1)
                         .Select(p => pattern.Substring(0, p));
var suffixes = Enumerable.Range(1, pattern.Length - 1)
                         .Select(p => pattern.Substring(p, pattern.Length - p));

If you don't need the results in a collection you might just want to use a simple for-loop as Dave Zych posted.

Upvotes: 3

Tamir Vered
Tamir Vered

Reputation: 10287

List<string> prefixes = new List<string>();
for (int i = 0; i < myString.Length; i++)
{
    prefixes.Add(myString.Substring(0,i));
}
List<string> sufixes = new List<string>();
for (int i = 0; i < myString.Length; i++)
{
    sufixes.Add(myString.Substring(i,myString Length - i));
}

Upvotes: 0

Dave Zych
Dave Zych

Reputation: 21887

Why not just loop?

string s = "bread";
for(int i = 1; i < s.Length; i++)
{
    Console.WriteLine(s.Substring(0, i)); //prefix
    Console.WriteLine(s.SubString(i, s.Length - i)); //suffix
}

Upvotes: 4

Related Questions