将文本格式化为 Pascal 或驼峰大小写的算法

发布于 2024-07-04 15:40:39 字数 289 浏览 8 评论 0 原文

使用这个问题作为基础是否有算法或编码将某些文本更改为 Pascal 或 Camel 大小写的示例。

例如:

mynameisfred

变成

Camel: myNameIsFred
Pascal: MyNameIsFred

Using this question as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing.

For example:

mynameisfred

becomes

Camel: myNameIsFred
Pascal: MyNameIsFred

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜雨飘雪 2024-07-11 15:40:39

唯一的方法是通过字典来运行单词的每个部分。

“mynameisfred”只是一个字符数组,将其分成“我的名字是弗雷德”意味着理解每个字符的连接意味着什么。

如果您的输入以某种方式分开,例如“我的名字是fred”或“my_name_is_fred”,您可以轻松做到这一点。

The only way to do that would be to run each section of the word through a dictionary.

"mynameisfred" is just an array of characters, splitting it up into my Name Is Fred means understanding what the joining of each of those characters means.

You could do it easily if your input was separated in some way, e.g. "my name is fred" or "my_name_is_fred".

深海夜未眠 2024-07-11 15:40:39

我在 http://www 上发现了一个帖子,里面有一群 Perl 人在争论这个问题。 .perlmonks.org/?node_id=336331

我希望这不是对这个问题的过多回答,但我想说你有一个问题,因为这将是一个非常开放式的算法,也可能有很多“失误”作为点击。 例如,假设您输入:-

camelCase("hithisisatest");

输出可能是:-

"hiThisIsATest"

或:-

"hitHisIsATest"

算法无法知道更喜欢哪个。 您可以添加一些额外的代码来指定您更喜欢更常见的单词,但再次会发生遗漏(Peter Norvig 在 可能在算法方面有所帮助,我写了一个 C# 实现 if C# 是您的语言)。

我同意马克的观点,并说你最好有一个接受分隔输入的算法,即 this_is_a_test 并将其转换。 这很容易实现,即用伪代码: -

SetPhraseCase(phrase, CamelOrPascal):
    if no delimiters
     if camelCase
      return lowerFirstLetter(phrase)
     else
      return capitaliseFirstLetter(phrase)
    words = splitOnDelimiter(phrase)
    if camelCase 
      ret = lowerFirstLetter(first word) 
     else
      ret = capitaliseFirstLetter(first word)
    for i in 2 to len(words): ret += capitaliseFirstLetter(words[i])
    return ret

capitaliseFirstLetter(word):
    if len(word) <= 1 return upper(word)
    return upper(word[0]) + word[1..len(word)]

lowerFirstLetter(word):
    if len(word) <= 1 return lower(word)
    return lower(word[0]) + word[1..len(word)]

如果您愿意,您也可以用适当的大小写算法替换我的 CapitaliseFirstLetter() 函数。

上述算法的 AC# 实现如下(带有测试工具的完整控制台程序):-

using System;

class Program {
  static void Main(string[] args) {

    var caseAlgorithm = new CaseAlgorithm('_');

    while (true) {
      string input = Console.ReadLine();

      if (string.IsNullOrEmpty(input)) return;

      Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'",
        input,
        caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase),
        caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase));
    }
  }
}

public class CaseAlgorithm {

  public enum CaseMode { PascalCase, CamelCase }

  private char delimiterChar;

  public CaseAlgorithm(char inDelimiterChar) {
    delimiterChar = inDelimiterChar;
  }

  public string SetPhraseCase(string phrase, CaseMode caseMode) {

    // You might want to do some sanity checks here like making sure
    // there's no invalid characters, etc.

    if (string.IsNullOrEmpty(phrase)) return phrase;

    // .Split() will simply return a string[] of size 1 if no delimiter present so
    // no need to explicitly check this.
    var words = phrase.Split(delimiterChar);

    // Set first word accordingly.
    string ret = setWordCase(words[0], caseMode);

    // If there are other words, set them all to pascal case.
    if (words.Length > 1) {
      for (int i = 1; i < words.Length; ++i)
        ret += setWordCase(words[i], CaseMode.PascalCase);
    }

    return ret;
  }

  private string setWordCase(string word, CaseMode caseMode) {
    switch (caseMode) {
      case CaseMode.CamelCase:
        return lowerFirstLetter(word);
      case CaseMode.PascalCase:
        return capitaliseFirstLetter(word);
      default:
        throw new NotImplementedException(
          string.Format("Case mode '{0}' is not recognised.", caseMode.ToString()));
    }
  }

  private string lowerFirstLetter(string word) {
    return char.ToLower(word[0]) + word.Substring(1);
  }

  private string capitaliseFirstLetter(string word) {
    return char.ToUpper(word[0]) + word.Substring(1);
  }
}

I found a thread with a bunch of Perl guys arguing the toss on this question over at http://www.perlmonks.org/?node_id=336331.

I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:-

camelCase("hithisisatest");

The output could be:-

"hiThisIsATest"

Or:-

"hitHisIsATest"

There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at http://norvig.com/spell-correct.html which might help algorithm-wise, I wrote a C# implementation if C#'s your language).

I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this_is_a_test and converts that. That'd be simple to implement, i.e. in pseudocode:-

SetPhraseCase(phrase, CamelOrPascal):
    if no delimiters
     if camelCase
      return lowerFirstLetter(phrase)
     else
      return capitaliseFirstLetter(phrase)
    words = splitOnDelimiter(phrase)
    if camelCase 
      ret = lowerFirstLetter(first word) 
     else
      ret = capitaliseFirstLetter(first word)
    for i in 2 to len(words): ret += capitaliseFirstLetter(words[i])
    return ret

capitaliseFirstLetter(word):
    if len(word) <= 1 return upper(word)
    return upper(word[0]) + word[1..len(word)]

lowerFirstLetter(word):
    if len(word) <= 1 return lower(word)
    return lower(word[0]) + word[1..len(word)]

You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished.

A C# implementation of the above described algorithm is as follows (complete console program with test harness):-

using System;

class Program {
  static void Main(string[] args) {

    var caseAlgorithm = new CaseAlgorithm('_');

    while (true) {
      string input = Console.ReadLine();

      if (string.IsNullOrEmpty(input)) return;

      Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'",
        input,
        caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase),
        caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase));
    }
  }
}

public class CaseAlgorithm {

  public enum CaseMode { PascalCase, CamelCase }

  private char delimiterChar;

  public CaseAlgorithm(char inDelimiterChar) {
    delimiterChar = inDelimiterChar;
  }

  public string SetPhraseCase(string phrase, CaseMode caseMode) {

    // You might want to do some sanity checks here like making sure
    // there's no invalid characters, etc.

    if (string.IsNullOrEmpty(phrase)) return phrase;

    // .Split() will simply return a string[] of size 1 if no delimiter present so
    // no need to explicitly check this.
    var words = phrase.Split(delimiterChar);

    // Set first word accordingly.
    string ret = setWordCase(words[0], caseMode);

    // If there are other words, set them all to pascal case.
    if (words.Length > 1) {
      for (int i = 1; i < words.Length; ++i)
        ret += setWordCase(words[i], CaseMode.PascalCase);
    }

    return ret;
  }

  private string setWordCase(string word, CaseMode caseMode) {
    switch (caseMode) {
      case CaseMode.CamelCase:
        return lowerFirstLetter(word);
      case CaseMode.PascalCase:
        return capitaliseFirstLetter(word);
      default:
        throw new NotImplementedException(
          string.Format("Case mode '{0}' is not recognised.", caseMode.ToString()));
    }
  }

  private string lowerFirstLetter(string word) {
    return char.ToLower(word[0]) + word.Substring(1);
  }

  private string capitaliseFirstLetter(string word) {
    return char.ToUpper(word[0]) + word.Substring(1);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文