Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities.
You can install Humanizer as a nuget package:
English only: Humanizer.Core
All languages: Humanizer
The following frameworks are supported: net4.8, net6, net7, and net8
Note: The nuget also targets netstandard2. This is to enable scenario where netstandard2 is required. For example Roslyn Analyzers or MSBuil tasks. Other frameworks (other than listed above) that can consume netstandard2 (example net4.6.1 through to net 4.7.2) are not supported. For example net4.6.1 through to net4.7.2 are not supported.
Also Humanizer symbols are source indexed with SourceLink and are included in the package so you can step through Humanizer code while debugging your code.
You choose which packages based on what NuGet package(s) you install. By default, the main Humanizer
2.0 package installs all supported languages exactly like it does in 1.x. If you're not sure, then just use the main Humanizer
package.
Here are the options:
Humanizer
package. This pulls in Humanizer.Core
and all language packages.Humanizer.Core
package. Only the English language resources will be availableHumanizer.Core.fr
. You can include multiple languages by installing however many language packages you want.The detailed explanation for how this works is in the comments here.
Humanize
string extensions allow you turn an otherwise computerized string into a more readable human-friendly one.
The foundation of this was set in the BDDfy framework where class names, method names and properties are turned into human readable sentences.
"PascalCaseInputStringIsTurnedIntoSentence".Humanize() => "Pascal case input string is turned into sentence" "Underscored_input_string_is_turned_into_sentence".Humanize() => "Underscored input string is turned into sentence" "Underscored_input_String_is_turned_INTO_sentence".Humanize() => "Underscored input String is turned INTO sentence"
Note that a string that contains only upper case letters, and consists only of one word, is always treated as an acronym (regardless of its length). To guarantee that any arbitrary string will always be humanized you must use a transform (see Transform
method below):
// acronyms are left intact "HTML".Humanize() => "HTML" // any unbroken upper case string is treated as an acronym "HUMANIZER".Humanize() => "HUMANIZER" "HUMANIZER".Transform(To.LowerCase, To.TitleCase) => "Humanizer"
You may also specify the desired letter casing:
"CanReturnTitleCase".Humanize(LetterCasing.Title) => "Can Return Title Case" "Can_return_title_Case".Humanize(LetterCasing.Title) => "Can Return Title Case" "CanReturnLowerCase".Humanize(LetterCasing.LowerCase) => "can return lower case" "CanHumanizeIntoUpperCase".Humanize(LetterCasing.AllCaps) => "CAN HUMANIZE INTO UPPER CASE"
The
LetterCasing
API and the methods accepting it are legacy from V0.2 era and will be deprecated in the future. Instead of that, you can useTransform
method explained below.
Much like you can humanize a computer friendly into human friendly string you can dehumanize a human friendly string into a computer friendly one:
"Pascal case input string is turned into sentence".Dehumanize() => "PascalCaseInputStringIsTurnedIntoSentence"
There is a Transform
method that supersedes LetterCasing
, ApplyCase
and Humanize
overloads that accept LetterCasing
.
Transform method signature is as follows:
string Transform(this string input, params IStringTransformer[] transformers)
And there are some out of the box implementations of IStringTransformer
for letter casing:
"Sentence casing".Transform(To.LowerCase) => "sentence casing" "Sentence casing".Transform(To.SentenceCase) => "Sentence casing" "Sentence casing".Transform(To.TitleCase) => "Sentence Casing" "Sentence casing".Transform(To.UpperCase) => "SENTENCE CASING"
LowerCase
is a public static property on To
class that returns an instance of private ToLowerCase
class that implements IStringTransformer
and knows how to turn a string into lower case.
The benefit of using Transform
and IStringTransformer
over ApplyCase
and LetterCasing
is that LetterCasing
is an enum and you're limited to use what's in the framework
while IStringTransformer
is an interface you can implement in your codebase once and use it with Transform
method allowing for easy extension.
You can truncate a string
using the Truncate
method:
"Long text to truncate".Truncate(10) => "Long text…"
By default the '…'
character is used to truncate strings. The advantage of using the '…'
character instead of "..."
is that the former only takes a single character and thus allows more text to be shown before truncation. If you want, you can also provide your own truncation string:
"Long text to truncate".Truncate(10, "---") => "Long te---"
The default truncation strategy, Truncator.FixedLength
, is to truncate the input string to a specific length, including the truncation string length.
There are two more truncator strategies available: one for a fixed number of (alpha-numerical) characters and one for a fixed number of words.
To use a specific truncator when truncating, the two Truncate
methods shown in the previous examples all have an overload that allow you to specify the ITruncator
instance to use for the truncation.
Here are examples on how to use the three provided truncators:
"Long text to truncate".Truncate(10, Truncator.FixedLength) => "Long text…" "Long text to truncate".Truncate(10, "---", Truncator.FixedLength) => "Long te---" "Long text to truncate".Truncate(6, Truncator.FixedNumberOfCharacters) => "Long t…" "Long text to truncate".Truncate(6, "---", Truncator.FixedNumberOfCharacters) => "Lon---" "Long text to truncate".Truncate(2, Truncator.FixedNumberOfWords) => "Long text…" "Long text to truncate".Truncate(2, "---", Truncator.FixedNumberOfWords) => "Long text---"
Note that you can also use create your own truncator by implementing the ITruncator
interface.
There is also an option to choose whether to truncate the string from the beginning (TruncateFrom.Left
) or the end (TruncateFrom.Right
).
Default is the right as shown in the examples above. The examples below show how to truncate from the beginning of the string:
"Long text to truncate".Truncate(10, Truncator.FixedLength, TruncateFrom.Left) => "… truncate" "Long text to truncate".Truncate(10, "---", Truncator.FixedLength, TruncateFrom.Left) => "---runcate" "Long text to truncate".Truncate(10, Truncator.FixedNumberOfCharacters, TruncateFrom.Left) => "…o truncate" "Long text to truncate".Truncate(16, "---", Truncator.FixedNumberOfCharacters, TruncateFrom.Left) => "---ext to truncate" "Long text to truncate".Truncate(2, Truncator.FixedNumberOfWords, TruncateFrom.Left) => "…to truncate" "Long text to truncate".Truncate(2, "---", Truncator.FixedNumberOfWords, TruncateFrom.Left) => "---to truncate"
Calling ToString
directly on enum members usually results in less than ideal output for users. The solution to this is usually to use DescriptionAttribute
data annotation and then read that at runtime to get a more friendly output. That is a great solution; but more often than not we only need to put some space between words of an enum member - which is what String.Humanize()
does well. For an enum like:
public enum EnumUnderTest { [Description("Custom description")] MemberWithDescriptionAttribute, MemberWithoutDescriptionAttribute, ALLCAPITALS }
You will get:
// DescriptionAttribute is honored EnumUnderTest.MemberWithDescriptionAttribute.Humanize() => "Custom description" // In the absence of Description attribute string.Humanizer kicks in EnumUnderTest.MemberWithoutDescriptionAttribute.Humanize() => "Member without description attribute" // Of course you can still apply letter casing EnumUnderTest.MemberWithoutDescriptionAttribute.Humanize().Transform(To.TitleCase) => "Member Without Description Attribute"
You are not limited to DescriptionAttribute
for custom description. Any attribute applied on enum members with a string Description
property counts.
This is to help with platforms with missing DescriptionAttribute
and also for allowing subclasses of the DescriptionAttribute
.
You can even configure the name of the property of attibute to use as description.
Configurator.EnumDescriptionPropertyLocator = p => p.Name == "Info"
If you need to provide localised descriptions you can use DisplayAttribute
data annotation instead.
public enum EnumUnderTest { [Display(Description = "EnumUnderTest_Member", ResourceType = typeof(Project.Resources))] Member }
You will get:
EnumUnderTest.Member.Humanize() => "content" // from Project.Resources found under "EnumUnderTest_Member" resource key
Hopefully this will help avoid littering enums with unnecessary attributes!
Dehumanizes a string into the Enum it was originally Humanized from! The API looks like:
public static TTargetEnum DehumanizeTo<TTargetEnum>(this string input)
And the usage is:
"Member without description attribute".DehumanizeTo<EnumUnderTest>() => EnumUnderTest.MemberWithoutDescriptionAttribute
And just like the Humanize API it honors the Description
attribute. You don't have to provide the casing you provided during humanization: it figures it out.
There is also a non-generic counterpart for when the original Enum is not known at compile time:
public static Enum DehumanizeTo(this string input, Type targetEnum, NoMatch onNoMatch = NoMatch.ThrowsException)
which can be used like:
"Member without description attribute".DehumanizeTo(typeof(EnumUnderTest)) => EnumUnderTest.MemberWithoutDescriptionAttribute
By default both methods throw a NoMatchFoundException
when they cannot match the provided input against the target enum.
In the non-generic method you can also ask the method to return null by setting the second optional parameter to NoMatch.ReturnsNull
.
You can Humanize
an instance of DateTime
or DateTimeOffset
and get back a string telling how far back or forward in time that is:
DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday" DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago" DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow" DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now" DateTimeOffset.UtcNow.AddHours(1).Humanize() => "an hour from now"
Humanizer supports both local and UTC dates as well as dates with offset (DateTimeOffset
). You could also provide the date you want the input date to be compared against. If null, it will use the current date as comparison base.
Also, culture to use can be specified explicitly. If it is not, current thread's current UI culture is used.
Here is the API signature:
public static string Humanize(this DateTime input, bool utcDate = true, DateTime? dateToCompareAgainst = null, CultureInfo culture = null) public static string Humanize(this DateTimeOffset input, DateTimeOffset? dateToCompareAgainst = null, CultureInfo culture = null)
Many localizations are available for this method. Here is a few examples:
// In ar culture DateTime.UtcNow.AddDays(-1).Humanize() => "أمس" DateTime.UtcNow.AddDays(-2).Humanize() => "منذ يومين" DateTime.UtcNow.AddDays(-3).Humanize() => "منذ 3 أيام" DateTime.UtcNow.AddDays(-11).Humanize() => "منذ 11 يوم" // In ru-RU culture DateTime.UtcNow.AddMinutes(-1).Humanize() => "минуту назад" DateTime.UtcNow.AddMinutes(-2).Humanize() => "2 минуты назад" DateTime.UtcNow.AddMinutes(-10).Humanize() => "10 минут назад" DateTime.UtcNow.AddMinutes(-21).Humanize() => "21 минуту назад" DateTime.UtcNow.AddMinutes(-22).Humanize() => "22 минуты назад" DateTime.UtcNow.AddMinutes(-40).Humanize() => "40 минут назад"
There are two strategies for DateTime.Humanize
: the default one as seen above and a precision based one.
To use the precision based strategy you need to configure it:
Configurator.DateTimeHumanizeStrategy = new PrecisionDateTimeHumanizeStrategy(precision: .75); Configurator.DateTimeOffsetHumanizeStrategy = new PrecisionDateTimeOffsetHumanizeStrategy(precision: .75); // configure when humanizing DateTimeOffset
The default precision is set to .75 but you can pass your desired precision too. With precision set to 0.75:
44 seconds => 44 seconds ago/from now 45 seconds => one minute ago/from now 104 seconds => one minute ago/from now 105 seconds => two minutes ago/from now 25 days => a month ago/from now
No dehumanization for dates as Humanize
is a lossy transformation and the human friendly date is not reversible
You can call Humanize
on a TimeSpan
to a get human friendly representation for it:
TimeSpan.FromMilliseconds(1).Humanize() => "1 millisecond" TimeSpan.FromMilliseconds(2).Humanize() => "2 milliseconds" TimeSpan.FromDays(1).Humanize() => "1 day" TimeSpan.FromDays(16).Humanize() => "2 weeks"
There is an optional precision
parameter for TimeSpan.Humanize
which allows you to specify the precision of the returned value.
The default value of precision
is 1 which means only the largest time unit is returned like you saw in TimeSpan.FromDays(16).Humanize()
.
Here is a few examples of specifying precision:
TimeSpan.FromDays(1).Humanize(precision:2) => "1 day" // no difference when there is only one unit in the provided TimeSpan TimeSpan.FromDays(16).Humanize(2) => "2 weeks, 2 days" // the same TimeSpan value with different precision returns different results TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks" TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour" TimeSpan.FromMilliseconds(1299630020).Humanize(4) => "2 weeks, 1 day, 1 hour, 30 seconds" TimeSpan.FromMilliseconds(1299630020).Humanize(5) => "2 weeks, 1 day, 1 hour, 30 seconds, 20 milliseconds"
By default when using precision
parameter empty time units are not counted towards the precision of the returned value.
If this behavior isn't desired for you, you can use the overloaded TimeSpan.Humanize
method with countEmptyUnits
parameter. Leading empty time units never count.
Here is an example showing the difference of counting empty units:
TimeSpan.FromMilliseconds(3603001).Humanize(3) => "1 hour, 3 seconds, 1 millisecond" TimeSpan.FromMilliseconds(3603001).Humanize(3, countEmptyUnits:true) => "1 hour, 3 seconds"
Many localizations are available for this method:
// in de-DE culture TimeSpan.FromDays(1).Humanize() => "Ein Tag" TimeSpan.FromDays(2).Humanize() => "2 Tage" // in sk-SK culture TimeSpan.FromMilliseconds(1).Humanize() => "1 milisekunda" TimeSpan.FromMilliseconds(2).Humanize() => "2 milisekundy" TimeSpan.FromMilliseconds(5).Humanize() => "5 milisekúnd"
Culture to use can be specified explicitly. If it is not, current thread's current UI culture is used. Example:
TimeSpan.FromDays(1).Humanize(culture: "ru-RU") => "один день"
In addition, a minimum unit of time may be specified to avoid rolling down to a smaller unit. For example:
TimeSpan.FromMilliseconds(122500).Humanize(minUnit: TimeUnit.Second) => "2 minutes, 2 seconds" // instead of 2 minutes, 2 seconds, 500 milliseconds TimeSpan.FromHours(25).Humanize(minUnit: TimeUnit.Day) => "1 Day" //instead of 1 Day, 1 Hour
In addition, a maximum unit of time may be specified to avoid rolling up to the next largest unit. For example:
TimeSpan.FromDays(7).Humanize(maxUnit:
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号