我正要编写一个C++函数,执行以下操作:
1 ---> "1st"
2 ---> "1nd"
3 ---> "3rd"
...
17657 --> "17657th"
...
例如,为该数字生成序数扩展字符串(它不需要对数字本身执行itoa()
)。但后来我想:“标准库或boost中的某些东西肯定已经做到了这一点?”
备注:
我知道写这个并不难,这里有一个implementation in Python,所以我不想重复代码,,
发布于 2016-11-01 04:24:28
这是我最终写的:
const char* ordinal_suffix(int n)
{
static const char suffixes [][3] = {"th", "st", "nd", "rd"};
auto ord = n % 100;
if (ord / 10 == 1) { ord = 0; }
ord = ord % 10;
if (ord > 3) { ord = 0; }
return suffixes[ord];
}
代码高尔夫解决方案很可爱,但它们确实优化了简洁性,而不是其他任何东西。这比这里的大多数其他答案更快(尽管可以通过将.cpp中的后缀放在函数体之外并使代码可内联来使其更快)、更清晰、更简洁。
发布于 2019-05-31 07:08:55
// Returns numbers with ordinal suffix as string
// Based on https://stackoverflow.com/questions/3109978/display-numbers-with-ordinal-suffix-in-php
std::string NumberToOrdinal(size_t number) {
std::string suffix = "th";
if (number % 100 < 11 || number % 100 > 13) {
switch (number % 10) {
case 1:
suffix = "st";
break;
case 2:
suffix = "nd";
break;
case 3:
suffix = "rd";
break;
}
}
return std::to_string(number) + suffix;
}
发布于 2014-02-04 17:15:07
我非常确定您可以在Display numbers with ordinal suffix in PHP上采用四行解决方案。不幸的是,我不认为在普通的C++库中有这样的东西。
https://stackoverflow.com/questions/21548099
复制相似问题