简体   繁体   中英

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

I have tried to use String.Contains to return true or false with a message for this method. When I ran my code, it will always display a false rather than a true if a search word is found in the string contains. In other words, my code simply returns false no matter what search word is found or not.

Here is the excerpt 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;
}

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.

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 (eg: 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;
}

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