gpt4 book ai didi

language-agnostic - 如何从字符串创建一个 SEO 友好的破折号分隔的 url?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:26:55 24 4
gpt4 key购买 nike

取一个字符串,例如:

In C#: How do I add "Quotes" around string in a comma delimited list of strings?

并将其转换为:

in-c-how-do-i-add-quotes-around-string-in-a-comma-delimited-list-of-strings

要求:

  • 用破折号分隔每个单词并删除所有标点符号(考虑到并非所有单词都用空格分隔。)
  • 函数接受最大长度,并获取小于该最大长度的所有标记。示例:ToSeoFriendly("hello world hello world", 14) 返回 "hello-world"
  • 所有单词都转换为小写。

另外,是否应该有最小长度?

最佳答案

这是我在 C# 中的解决方案

private string ToSeoFriendly(string title, int maxLength) {
var match = Regex.Match(title.ToLower(), "[\\w]+");
StringBuilder result = new StringBuilder("");
bool maxLengthHit = false;
while (match.Success && !maxLengthHit) {
if (result.Length + match.Value.Length <= maxLength) {
result.Append(match.Value + "-");
} else {
maxLengthHit = true;
// Handle a situation where there is only one word and it is greater than the max length.
if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
}
match = match.NextMatch();
}
// Remove trailing '-'
if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
return result.ToString();
}

关于language-agnostic - 如何从字符串创建一个 SEO 友好的破折号分隔的 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/465659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com