0

I need to create a function that receives two strings, representing the word to be completed and the reference word, as well as a character corresponding to the proposed letter, and returns a string corresponding to the word to be completed in which all occurrences of the proposed letter have been added, relative to the reference word.

Example: CompleterMot (".. IM ..", "ANIMAL", 'A') should return "A.IMA.". I don't understand how I can add all occurrences of the letter in the word that will be completed.

static string CompleterMot(string motincomplet, string motoriginal, char lettrepropos)
{
    string output = " ";

    for (int i = 0; i < motoriginal.Length; i++)
    {
        if((motoriginal[i] == lettrepropos))
        {
            output = motincomplet;
            if(output[i] != lettrepropos)
                output += (char)(lettrepropos);
        }
    }

    return output;
}

In final I had ..IM..A and I don't know how to fix my code.

1
  • For non french speakers : CompleterMot is CompletWord, motincomplet is IncompleteWord, motoriginal is OriginalWord and lettrepropos is SuggestedLetter Commented Aug 18, 2019 at 7:18

1 Answer 1

2

In your loop, you are doing this : output = motincomplet; this override the previous result. Then you append the expected letter to the output that gives "..IM.." + 'A' as result.

You can use a StringBuilder for string manipulation, that's pretty nice and allow you to directly change a character at a given index :

static string CompleterMot(string motincomplet, string motoriginal, char lettrepropos)
{
    var sb = new System.Text.StringBuilder(motincomplet);

    for (int i = 0; i < motoriginal.Length; i++)
    {
        if (motoriginal[i] == lettrepropos)
        {
            sb[i] = lettrepropos;
        }
    }
    return sb.ToString();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.