簡體   English   中英

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

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

我有很多電影(目前有 1000 部,但很容易達到 5000 部)。 我想為電影設置“正確的”標題,這意味着將“A”、“An”、“The”移動到標題的末尾(即“納尼亞傳奇”變成“納尼亞傳奇”)。

我可以用子字符串做一些 if 語句,但我正在尋找最有效/最快的方法來做到這一點。

建議?

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");

可能應該這樣做。 正則表達式在開頭匹配 The、A 和 An,並將其移至末尾。

快速 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

我不認為1000 string是那么多。 你可以的。

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