简体   繁体   English

在 c# 中更改字符串以将“A”、“An”、“The”移动到字符串末尾的最佳方法

[英]Best way to alter a string to move “A”, “An”, “The” to end of the string in c#

I have a large list of movies (1000 currently, but can easily reach 5000).我有很多电影(目前有 1000 部,但很容易达到 5000 部)。 I want to set "proper" titles for the movies, which means moving "A", "An", "The" to the end of the title (ie 'The Chronicles of Narnia' become 'Chronicles of Narnia, The').我想为电影设置“正确的”标题,这意味着将“A”、“An”、“The”移动到标题的末尾(即“纳尼亚传奇”变成“纳尼亚传奇”)。

I can do some if statements with substrings, but I am looking for the most efficient/fastest way to do this.我可以用子字符串做一些 if 语句,但我正在寻找最有效/最快的方法来做到这一点。

Suggestions?建议?

string title = "The Chronicles of Narnia";
string newTitle = Regex.Replace(title, "^(the|a|an) (.*)$", "$2, $1", RegexOptions.IgnoreCase);

Console.WriteLine(newTitle);
Regex.Replace(s, "(?i)^(The|A|An) (.*)$","$2, $1");

should probably do it.可能应该这样做。 The regex matches The, A and An in the beginning and moves it to the end.正则表达式在开头匹配 The、A 和 An,并将其移至末尾。

Quick PowerShell test:快速 PowerShell 测试:

PS Home:\> 'Conan the Barbarian','The Lord of the Rings','The Matrix','There Will Be Blood'-creplace'(?i)^(The|A|An) (.*)$','$2, $1'
Conan the Barbarian
Lord of the Rings, The
Matrix, The
There Will Be Blood

I dont think 1000 string is that much.我不认为1000 string是那么多。 You could do.你可以的。

string movieStr = "The Test Movie";
            string[] MovieStrArr = movieStr.Split(' ');
            string resultStr = string.Empty;
            string tempString = string.Empty;

            if (MovieStrArr[0] == "The" || MovieStrArr[0] == "A" || MovieStrArr[0] == "An")
            {
                tempString = MovieStrArr[0];
                MovieStrArr[0] = MovieStrArr[MovieStrArr.Length - 1];
                MovieStrArr[MovieStrArr.Length - 2] = MovieStrArr[MovieStrArr.Length - 2] + ",";
                MovieStrArr[MovieStrArr.Length - 1] = tempString;
                resultStr = string.Join(" ", MovieStrArr);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM