これがうまくいくかどうかはわかりませんが、これが私が思いついたものです:
string input = "A bgt abc hyi. Abc Ab df h";
Dictionary<string, string> map = new Dictionary<string, string>();
map.Add("abc", "cde");
map.Add("ab df", "de");
string temp = input;
foreach (var entry in map)
{
string key = entry.Key;
string value = entry.Value;
temp = Regex.Replace(temp, key, match =>
{
bool isUpper = char.IsUpper(match.Value[0]);
char[] result = value.ToCharArray();
result[0] = isUpper
? char.ToUpper(result[0])
: char.ToLower(result[0]);
return new string(result);
}, RegexOptions.IgnoreCase);
}
label1.Text = temp; // output is A bgt cde hyi. Cde De h
EDIT
変更された質問を読んだ後、ここに私の変更されたコードがあります(@Sephalliaのコードと同様の手順であることがわかります..および同様の変数名lol)
コードはもう少し複雑になりました..でも大丈夫だと思います
string input =
@"As he didn't achieve success, he was fired.
As he DIDN'T ACHIEVE SUCCESS, he was fired.
As he Didn't Achieve Success, he was fired.
As he Didn't achieve success, he was fired.";
Dictionary<string, string> map = new Dictionary<string, string>();
map.Add("didn't achieve success", "failed miserably");
string temp = input;
foreach (var entry in map)
{
string key = entry.Key;
string value = entry.Value;
temp = Regex.Replace(temp, key, match =>
{
bool isFirstUpper, isEachUpper, isAllUpper;
string sentence = match.Value;
char[] sentenceArray = sentence.ToCharArray();
string[] words = sentence.Split(' ');
isFirstUpper = char.IsUpper(sentenceArray[0]);
isEachUpper = words.All(w => char.IsUpper(w[0]) || !char.IsLetter(w[0]));
isAllUpper = sentenceArray.All(c => char.IsUpper(c) || !char.IsLetter(c));
if (isAllUpper)
return value.ToUpper();
if (isEachUpper)
{
// capitalize first of each word... use regex again :P
string capitalized = Regex.Replace(value, @"\b\w", charMatch => charMatch.Value.ToUpper());
return capitalized;
}
char[] result = value.ToCharArray();
result[0] = isFirstUpper
? char.ToUpper(result[0])
: char.ToLower(result[0]);
return new string(result);
}, RegexOptions.IgnoreCase);
}
textBox1.Text = temp;
/* output is :
As he failed miserably, he was fired.
As he FAILED MISERABLY, he was fired.
As he Failed Miserably, he was fired.
As he Failed miserably, he was fired.
*/