【问题标题】:Get a string that will be highest alphabetical order获取一个最高字母顺序的字符串
【发布时间】:2011-11-13 20:54:53
【问题描述】:

这很难说对。基本上,我有一个列表,我需要取回一个字符串,该字符串将是该字母顺序列表中的最后一个。例如:

如果我有清单:

{ "01", "0a2", "test" }

我需要取回按字母顺序排列的字符串,例如“tf”

【问题讨论】:

  • 你想要一些东西alphabetically higher then 'test'?您不能将它们转换为 char 并在 charcode 中添加一个,
  • "test" 会在 "tf" 之前。

标签: c# string list


【解决方案1】:

这是一个有点老套的答案,但我希望这会有所帮助。假设你的字符串在一个排序列表中,我有一个小“快速和肮脏”的方法,它按字母顺序生成下一个项目:

var items = new System.Collections.Generic.SortedList<string, string>();

items.Add("01", "01");
items.Add("02a", "02a");
items.Add("test", "test");

var nextItem = items.Last().Key;

int pos = nextItem.Length - 1;
while (pos >= 0)
{
   if ((nextItem[pos] != 'z') && (nextItem[pos] != 'Z'))
   {
      nextItem = nextItem.Substring(0, pos - 1) +  Convert.ToChar(Convert.ToInt32(nextItem[pos]) + 1) + nextItem.Substring(pos + 1);
      break;
    }
    pos--;
 }

 if (pos == -1)
 {
    nextItem += "a";
 }

【讨论】:

  • 有趣的答案。让我试试看:)
  • 我有一个小问题.. 这是它最终做的事情:screensnapr.com/v/bI2nyb.png - 一开始很好,然后一遍又一遍地做同样的事情。有什么想法吗?
【解决方案2】:

你不会说什么语言?

大多数语言都有数组排序功能,按字母顺序排序。只需进行排序,然后选择数组的最后一个元素。

【讨论】:

  • 我知道如何排序,但我需要创建一个新的字符串,它按字母顺序比数组中的字符串大...
【解决方案3】:

如果您总是想要一个在所有现有字符串之后按字母顺序“最后一个”的字符串,这应该可以;)

var words = new []{"01","0a2","test"}; 

int maxLength = words.ToList().Max(x => x.Length);

string newWord ="";

for(int i=0;i<maxLength +1;i++){

  newWord+= "z";            

}

【讨论】:

  • “test”后面的词是 - 按字母顺序 - “tesu”,而不是像您的示例中的“testz”。
猜你喜欢
  • 2016-11-25
  • 2019-02-28
  • 1970-01-01
  • 2014-06-13
  • 2015-07-22
  • 2015-09-06
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
相关资源
最近更新 更多