# Function to match the case of a text as per another text

I am translating a text into another language using Google APIs.

Sometimes the translated text returned from the API does not match the case of the text provided - e.g. when translating the text "Now Activated" to German, I get the translated text response as "jetzt aktiviert" instead of "Jetzt Aktiviert".

I wrote a function which can change the case of translated text to match the input text:

public string MaintainCase(string text, string translatedText)
{
// Split the inputs provided into string arrays
var textStrArray = text.Split(' ');
var translatedTextStrArray = translatedText.Split(' ');

// Count the no of words of both the texts provided
var noOfWordsInText = textStrArray.Length;
var noOfWordsInTranslatedText = translatedTextStrArray.Length;

// Check if the word count matches
bool wordCountMatches =
noOfWordsInText == noOfWordsInTranslatedText
? true
: false;

// Start changing the case of translated text as per text
for (int i = 0; i < noOfWordsInText; i++)
{
// Take the word no i of text and translated text
var textWord = textStrArray[i];
var translatedTextWord = translatedTextStrArray[i];

// Using string builder to modify the first character of translated text
// based on the case identified of the first character of text
var strBuilder = new StringBuilder(translatedTextWord);
var changedChar =
char.IsUpper(textWord[0])
? char.ToUpper(translatedTextWord[0])
: char.ToLower(translatedTextWord[0]);

strBuilder[0] = changedChar;
translatedTextStrArray[i] = strBuilder.ToString();

// If the word count does not match, after changing the case of only first word, break the loop
if (!wordCountMatches)
{
break;
}
}

// Return the modified translated text
return string.Join(" ", translatedTextStrArray);
}


Kindly suggest if this can be made more efficient (usage of string builders etc) and if I need to add some additional checks which I may have missed.

• Frame challenge: is the result really what we want? E.g. translating German mein Buch to English, we normally want my book, not my Book. Similarly, when going the other way, we must respect the capitalisation that the rules of the language demand, rather than slavishly following the source language. – Toby Speight Oct 1 at 7:46
• In the application this can be made optional by providing a default bool parameter 'maintainCase = false'. However is the code fine for the scenario where we do want to utilize this functionality? – Akshunya Oct 1 at 7:52
• This looks like trouble to me and as a method that will never be good enough because of all strange possibilities in real world texts. Have you considered the functionality provided by CultureInfo.TextInfo for instance ToTitleCase() and the like? – Henrik Hansen Oct 1 at 10:03