Home > Enterprise >  How to return bool with message inside the Search Word method C#?
How to return bool with message inside the Search Word method C#?

Time:10-16

I have tried to use String.Contains to return true or false with message for this method. However, I received return false if I type cat (correct word contain data). As for when I type dog which is a valid since the return is false. So a problem is that how do I return a true for "cat". In addition, here are my result when I ran some test on my code.

Enter a search word: cat
The string 'My cat is Oliver' contains 'dog'? -> 'False'
False
Enter a search word: dog
The string 'My cat is Oliver' contains 'dog'? -> 'False'
False

Here is my code that I tried to return true or false.

string data = "My cat is Oliver";
string searchKey = "cat";

Console.Write("Enter a search word: ");
string searchWord = Console.ReadLine();
Console.WriteLine(SearchWord(searchKey, data));

bool SearchWord (string searchKey, string data)
{
    string text = "My cat is Oliver";
    string searchText = "searchKey";
    string searchText2 = "dog";

    bool result = text.Contains(searchText);
    bool result1 = text.Contains(searchText2);

    if (result == true)
    {
        Console.WriteLine("The string '{0}' contains '{1}'? -> '{2}'", text, searchText, result);  
    }
    else
    {
        Console.WriteLine("The string '{0}' contains '{1}'? -> '{2}'", text, searchText2, result1);
    }

    return result;
}

CodePudding user response:

Let's do some cleanup with your code.

First, terminology: "data" isn't a good variable name. It's not very descriptive of what it represents. It's really your "source" string, so let's use that. "search key" is fine, but a better name would be the "search term" (which we'll just call "term"). We'll also reflect this in the method name.

Putting that into the method signature.

bool SearchForTerm(string source, string term)

Now the body of the method. It's not a good idea to have this method do two actions, return true/false and print to the console. Just have this method do one thing. Printing to the console should be the caller's responsibility.

Of course, we actually need to use the source and term parameters, not hard coded strings.

return source.Contains(term);
// that's it. that's the entire implementation of the method.

To call it, you have a hard coded source string (which you can change later to console input), and a term which you prompt the user for. Again, you need to use the actual variable from that input capture in the method call.

string source = "My cat is Oliver";
Console.Write("Enter a search word: ");
string term = Console.ReadLine();
bool containedTerm = SearchForTerm(source, term);

After you call the method, then you can print to the screen conditionally on the result.

if (containedTerm)
{
    Console.WriteLine("The string '{0}' contains '{1}'", source, term); 
}
else
{
    Console.WriteLine("The string '{0}' does not contain '{1}'", source, term); 
}

Putting it all together

bool SearchForTerm(string source, string term)
{
    return source.Contains(term);
}
string source = "My cat is Oliver";
Console.Write("Enter a search word: ");
string term = Console.ReadLine();
bool containedTerm = SearchForTerm(source, term);

if (containedTerm) // braces removed for brevity, I do not recommend you do this
    Console.WriteLine("The string '{0}' contains '{1}'", source, term); 
else
    Console.WriteLine("The string '{0}' does not contain '{1}'", source, term);

Granted, with how trivial the code in SearchForTerm currently is, it's arguable that the method shouldn't even exist. Consider folding it directly into the caller's code.

CodePudding user response:

You can use TryX pattern like this:

void Main()
{
    bool isFound = SearchWord("My cat is Oliver", "cat", out string message);
    Console.WriteLine(isFound);
    Console.WriteLine(message);

    //
    isFound = SearchWord("My cat is Oliver", "dog", out message);
    Console.WriteLine(isFound);
    Console.WriteLine(message);
}

public bool SearchWord(string data, string searchKey, out string message)
{
    if(data.Contains(searchKey))
    {
        message = $"The string '{data}' contains '{searchKey}'";
        return true;
    }
    else
    {
        message = $"The string '{data}' doesn't contain '{searchKey}'";
        return false;
    }
}

You can see this pattern a lot (e.g: int.TryParse()), so here you can use the boolean as the return value from the method and check the out parameter message for any error/successful message.

or

You can use another way, so create a custom class for your result like :

public class MyResult
{
    public bool Succeed { get; set; }
    public string Message { get; set; }
}

And use like this:

void Main()
{
    var result = SearchWord("My cat is Oliver", "cat");
    Console.WriteLine(result.Succeed);
    Console.WriteLine(result.Message);

    //
    result = SearchWord("My cat is Oliver", "dog");
    Console.WriteLine(result.Succeed);
    Console.WriteLine(result.Message);
}


public MyResult SearchWord(string data, string searchKey)
{
    var retval = new MyResult();
    
    if (data.Contains(searchKey))
    {
        retval.Message = $"The string '{data}' contains '{searchKey}'";
        retval.Succeed = true;
    }
    else
    {
        retval.Message = $"The string '{data}' doesn't contain '{searchKey}'";
        retval.Succeed = false;
    }
    
    return retval;
}
  • Related