简体   繁体   中英

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). 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').

I can do some if statements with substrings, but I am looking for the most efficient/fastest way to do this.

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.

Quick PowerShell test:

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. 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);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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