Search code examples
c#stringifc

Change every character within a string without spaces to lower case apart from the first letters


I have strings, which I read from a document looking like the following:

IFCPERSONANDORGANIZATION

My goal is to create a new entity of a class that is called the same. Therefore I need this string to match the class name. However, the class name (which I cannot change) looks like the following:

IfcPersonAndOrganization

Is there any way I can change that input string so it matches the class-name regarding upper and lower cases?

Unfortunately .ToTitle does not work for my purpose as there are no spaces in my input string. I do have, however, a text file that contains all the class names possible (~800). So I could probably write a method, that checks the text file for the matching name and changes my input string accordingly. I am afraid that this will take pretty long and would be very inefficient though. EDIT: The text file contains one class name per line.

Anyone has an idea that might be more elegant and faster?


Solution

  • Sure, you could read your file contents into a list and then check if the input string is contained in the list (using a case-insensitive comparision). If it is, you just replace the string with the one from the list:

    // The input string we want to format
    var input = "IFCPERSONANDORGANIZATION";
    
    // Read the file containing your class names into an array
    var filePath = @"f:\public\temp\classnames.txt";
    var knownClassNames = File.ReadAllLines(filePath);
    
    // See if the list contains the name using a case-insensitive comarison. 
    // If it does, `FirstOrDefault` will return a non-null value, so we assign the result
    // Otherwise, if it returns null (which is checked by `??`) we leave it as is.
    input = knownClassNames
        .FirstOrDefault(name => name.Equals(input, StringComparison.OrdinalIgnoreCase)) 
        ?? input;
    

    This could be put into a simple function, which you could call from anywhere:

    public static string CorrectClassNameCasing(string input)
    {
        var filePath = @"f:\public\temp\classnames.txt";
        var knownClassNames = File.ReadAllLines(filePath);
    
        return knownClassNames
            .FirstOrDefault(name => name.Equals(input, StringComparison.OrdinalIgnoreCase)) ?? input;
    }
    

    For my example, I created a file that contains only the one class name that you mentioned in your example:

    static void Main()
    {
        Console.WriteLine(CorrectClassNameCasing("IFCPERSONANDORGANIZATION"));
        Console.WriteLine(CorrectClassNameCasing("THISDOESNOTEXIST"));
    
        Console.Write("\nDone!\nPress any key to continue...");
        Console.ReadKey();
    }
    

    And the results look like:

    enter image description here