web-dev-qa-db-fra.com

Comment convertir du texte en cas Pascal?

J'ai un nom de variable, dites "WARD_VS_VITAL_SIGNS", et je veux le convertir au format de cas Pascal: "WardVsVitalSigns"

WARD_VS_VITAL_SIGNS -> WardVsVitalSigns

Comment puis-je effectuer cette conversion?

18
wlz

Tout d'abord, vous demandez la casse du titre et non la casse du chameau, car dans le cas du chameau, la première lettre du mot est en minuscule et votre exemple montre que vous voulez que la première lettre soit en majuscule.

En tout cas, voici comment vous pourriez obtenir le résultat souhaité:

string textToChange = "WARD_VS_VITAL_SIGNS";
System.Text.StringBuilder resultBuilder = new System.Text.StringBuilder();

foreach(char c in textToChange)
{
    // Replace anything, but letters and digits, with space
    if(!Char.IsLetterOrDigit(c))
    {
        resultBuilder.Append(" ");
    }
    else 
    { 
        resultBuilder.Append(c); 
    }
}

string result = resultBuilder.ToString();

// Make result string all lowercase, because ToTitleCase does not change all uppercase correctly
result = result.ToLower();

// Creates a TextInfo based on the "en-US" culture.
TextInfo myTI = new CultureInfo("en-US",false).TextInfo;

result = myTI.ToTitleCase(result).Replace(" ", String.Empty);

Remarque: result est désormais WardVsVitalSigns.

Si vous vouliez en fait un étui à chameau, alors après tout ce qui précède, utilisez simplement cette fonction d'assistance:

public string LowercaseFirst(string s)
{
    if (string.IsNullOrEmpty(s))
    {
        return string.Empty;
    }

    char[] a = s.ToCharArray();
    a[0] = char.ToLower(a[0]);

    return new string(a);
}

Vous pouvez donc l'appeler comme ceci:

result = LowercaseFirst(result);
13
Karl Anderson

Vous n'avez pas besoin d'expression régulière pour cela.

var yourString = "WARD_VS_VITAL_SIGNS".ToLower().Replace("_", " ");
TextInfo info = CultureInfo.CurrentCulture.TextInfo;
yourString = info.ToTitleCase(yourString).Replace(" ", string.Empty);
Console.WriteLine(yourString);

Vous pouvez modifier le code comme vous le souhaitez.

40
Nilesh

Voici ma solution rapide LINQ & regex pour gagner du temps à quelqu'un:

using System;
using System.Linq;
using System.Text.RegularExpressions;

public string ToPascalCase(string original)
{
    Regex invalidCharsRgx = new Regex("[^_a-zA-Z0-9]");
    Regex whiteSpace = new Regex(@"(?<=\s)");
    Regex startsWithLowerCaseChar = new Regex("^[a-z]");
    Regex firstCharFollowedByUpperCasesOnly = new Regex("(?<=[A-Z])[A-Z0-9]+$");
    Regex lowerCaseNextToNumber = new Regex("(?<=[0-9])[a-z]");
    Regex upperCaseInside = new Regex("(?<=[A-Z])[A-Z]+?((?=[A-Z][a-z])|(?=[0-9]))");

    // replace white spaces with undescore, then replace all invalid chars with empty string
    var pascalCase = invalidCharsRgx.Replace(whiteSpace.Replace(original, "_"), string.Empty)
        // split by underscores
        .Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries)
        // set first letter to uppercase
        .Select(w => startsWithLowerCaseChar.Replace(w, m => m.Value.ToUpper()))
        // replace second and all following upper case letters to lower if there is no next lower (ABC -> Abc)
        .Select(w => firstCharFollowedByUpperCasesOnly.Replace(w, m => m.Value.ToLower()))
        // set upper case the first lower case following a number (Ab9cd -> Ab9Cd)
        .Select(w => lowerCaseNextToNumber.Replace(w, m => m.Value.ToUpper()))
        // lower second and next upper case letters except the last if it follows by any lower (ABcDEf -> AbcDef)
        .Select(w => upperCaseInside.Replace(w, m => m.Value.ToLower()));

    return string.Concat(pascalCase);
}

Exemple de sortie:

"WARD_VS_VITAL_SIGNS"          "WardVsVitalSigns"
"Who am I?"                    "WhoAmI"
"I ate before you got here"    "IAteBeforeYouGotHere"
"Hello|Who|Am|I?"              "HelloWhoAmI"
"Live long and prosper"        "LiveLongAndProsper"
"Lorem ipsum dolor..."         "LoremIpsumDolor"
"CoolSP"                       "CoolSp"
"AB9CD"                        "Ab9Cd"
"CCCTrigger"                   "CccTrigger"
"CIRC"                         "Circ"
"ID_SOME"                      "IdSome"
"ID_SomeOther"                 "IdSomeOther"
"ID_SOMEOther"                 "IdSomeOther"
"CCC_SOME_2Phases"             "CccSome2Phases"
"AlreadyGoodPascalCase"        "AlreadyGoodPascalCase"
"999 999 99 9 "                "999999999"
"1 2 3 "                       "123"
"1 AB cd EFDDD 8"              "1AbCdEfddd8"
"INVALID VALUE AND _2THINGS"   "InvalidValueAnd2Things"
14
chviLadislav

Solution de point-virgule unique:

public static string PascalCase(this string Word)
{
    return string.Join("" , Word.Split('_')
                 .Select(w => w.Trim())
                 .Where(w => w.Length > 0)
                 .Select(w => w.Substring(0,1).ToUpper() + w.Substring(1).ToLower()));
}
7
WhiteleyJ

Méthode d'extension pour System.String avec du code compatible .NET Core en utilisant System et System.Linq.

ne modifie pas la chaîne d'origine.

. NET Fiddle pour le code ci-dessous

using System;
using System.Linq;

public static class StringExtensions
{
    /// <summary>
    /// Converts a string to PascalCase
    /// </summary>
    /// <param name="str">String to convert</param>

    public static string ToPascalCase(this string str){

        // Replace all non-letter and non-digits with an underscore and lowercase the rest.
        string sample = string.Join("", str?.Select(c => Char.IsLetterOrDigit(c) ? c.ToString().ToLower() : "_").ToArray());

        // Split the resulting string by underscore
        // Select first character, uppercase it and concatenate with the rest of the string
        var arr = sample?
            .Split(new []{'_'}, StringSplitOptions.RemoveEmptyEntries)
            .Select(s => $"{s.Substring(0, 1).ToUpper()}{s.Substring(1)}");

        // Join the resulting collection
        sample = string.Join("", arr);

        return sample;
    }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine("WARD_VS_VITAL_SIGNS".ToPascalCase()); // WardVsVitalSigns
        Console.WriteLine("Who am I?".ToPascalCase()); // WhoAmI
        Console.WriteLine("I ate before you got here".ToPascalCase()); // IAteBeforeYouGotHere
        Console.WriteLine("Hello|Who|Am|I?".ToPascalCase()); // HelloWhoAmI
        Console.WriteLine("Live long and prosper".ToPascalCase()); // LiveLongAndProsper
        Console.WriteLine("Lorem ipsum dolor sit amet, consectetur adipiscing elit.".ToPascalCase()); // LoremIpsumDolorSitAmetConsecteturAdipiscingElit
    }
}
4
Jani Hyytiäinen
var xs = "WARD_VS_VITAL_SIGNS".Split('_');

var q =

    from x in xs

    let first_char = char.ToUpper(x[0]) 
    let rest_chars = new string(x.Skip(1).Select(c => char.ToLower(c)).ToArray())

    select first_char + rest_chars;
2
Rodrick Chapman

Certaines réponses sont correctes, mais je ne comprends vraiment pas pourquoi elles ont d'abord défini le texte sur LowerCase, car le ToTitleCase s'en occupera automatiquement:

var text = "WARD_VS_VITAL_SIGNS".Replace("_", " ");

TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
text = textInfo.ToTitleCase(text).Replace(" ", string.Empty);

Console.WriteLine(text);
0
Dr TJ