HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Creating text without repetition

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
creatingtextwithoutrepetition

Problem

The basic idea is not to allow the same text and add +1 at the end.

Imagine that I have a datagrid (WPF) with names, and every time I click the add button, I will put a new name on the list automatically by running this method to ensure that no two names are alike.

My standard used: if there is repeated text, add to the end "(" + count + ")", similar to Windows Explorer.

Are there ways to make this using LINQ or Regex?

private void Test()
{
    var result = CreateText("t", new string[] { "t", "t(1)", "t(2)", "t(3)", "t(4)", "t(5)", "t(6)", "t(7)", "t(8)", "t(9)", "t(10)" });
    Assert.IsTrue(result == "t(11)");
}

public static String CreateText(string newText, String[] texts)
{
    int addCount = 0;
    foreach (String text in texts)
    {
        if (text.IndexOf(newText) == 0)
        {
            if (text == newText && addCount == 0)
            {
                addCount = 1;
                continue;
            }
            else
            {
                if (text.LastIndexOf('(') == newText.Length && text.LastIndexOf(')') == text.Length - 1)
                {
                    try
                    {
                        var initial = text.LastIndexOf('(') + 1;
                        var size = text.LastIndexOf(')') - initial;
                        int count = Int16.Parse(text.Substring(initial, size));
                        if (addCount  0)
    {
        newText += "(" + addCount + ")";
    }
    return newText;
}

Solution

Here is shorter method with regex

private static String CreateText(string textIdentifier, IEnumerable texts)
    {
        const int defaultNumber = 1;

        Regex regex = new Regex(@"\(\s*(?\d+)\s*\)");

        var numbers = 
            texts.Select(p => p.Trim()).Where(p => p.StartsWith(textIdentifier))
            .Select(str => { var m = regex.Match(str); return m.Success ? int.Parse(m.Groups["num"].Value) + 1 : defaultNumber; });

        int max = numbers.Any() ? numbers.Max() : 0;

        return max == 0 ? textIdentifier : string.Format("{0}({1})", textIdentifier, max);
    }


+1 to @dreza for tests ;)

Code Snippets

private static String CreateText(string textIdentifier, IEnumerable<string> texts)
    {
        const int defaultNumber = 1;

        Regex regex = new Regex(@"\(\s*(?<num>\d+)\s*\)");

        var numbers = 
            texts.Select(p => p.Trim()).Where(p => p.StartsWith(textIdentifier))
            .Select(str => { var m = regex.Match(str); return m.Success ? int.Parse(m.Groups["num"].Value) + 1 : defaultNumber; });

        int max = numbers.Any() ? numbers.Max() : 0;

        return max == 0 ? textIdentifier : string.Format("{0}({1})", textIdentifier, max);
    }

Context

StackExchange Code Review Q#18570, answer score: 4

Revisions (0)

No revisions yet.