स्ट्रिंग को बूल में कैसे बदलें


90

मेरे पास एक string"0" या "1" हो सकता है, और यह गारंटी है कि यह कुछ और नहीं होगा।

तो सवाल यह है: यह एक में बदलने के लिए सबसे अच्छा, सरल और सबसे सुंदर तरीका boolक्या है ?


3
यदि कोई अनपेक्षित मान इनपुट में हो सकता है, तो TryParse ( stackoverflow.com/questions/18329001/… ) का उपयोग करने पर विचार करें
— माइकल फ्रीजिम

जवाबों:


171

वास्तव में काफी सरल:

bool b = str == "1";

धन्यवाद! मुझे विश्वास नहीं हो रहा है कि मैं इस पर कितना सोच रहा था
— grizzasd

79

इस प्रश्न की विशिष्ट आवश्यकताओं को अनदेखा करना, और जब तक एक बूल के लिए एक स्ट्रिंग कास्ट करने के लिए इसका अच्छा विचार नहीं है, तब तक कन्वर्ट क्लास पर टोबूलियन () पद्धति का उपयोग करने का एक तरीका होगा :

bool val = Convert.ToBoolean("true");

या जो भी अजीब मैपिंग आप कर रहे हैं उसे करने के लिए एक विस्तार विधि:

public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        switch (value.ToLower())
        {
            case  "true":
                return true;
            case "t":
                return true;
            case "1":
                return true;
            case "0":
                return false;
            case "false":
                return false;
            case "f":
                return false;
            default:
                throw new InvalidCastException("You can't cast that value to a bool!");
        }
    }
}

1
Convert.ToBoolean का व्यवहार stackoverflow.com/questions/7031964/…
— माइकल फ्रीजिम

1
बूलियन महसूस करें। ट्रीपर्स बेहतर है, जब बहुत सारे मूल्यों को परिवर्तित करने की आवश्यकता होती है क्योंकि यह Convert.ToBrean कीFormatException तरह नहीं फेंकता है ।
— user3613932

47

मुझे पता है कि यह आपके सवाल का जवाब नहीं देता, लेकिन सिर्फ दूसरे लोगों की मदद करने के लिए। यदि आप "सच्चे" या "झूठे" तार को बूलियन में बदलने की कोशिश कर रहे हैं:

बूलियन का प्रयास करें

bool val = Boolean.Parse("true"); ==> true
bool val = Boolean.Parse("True"); ==> true
bool val = Boolean.Parse("TRUE"); ==> true
bool val = Boolean.Parse("False"); ==> false
bool val = Boolean.Parse("1"); ==> Exception!
bool val = Boolean.Parse("diffstring"); ==> Exception!

कुछ XML डेटा पढ़ने वाली पॉवरशेल स्क्रिप्ट के लिए इसकी आवश्यकता है और यह एकदम सही है!
— अल्टरनेटेक्स

20
bool b = str.Equals("1")? true : false;

या इससे भी बेहतर, जैसा कि नीचे टिप्पणी में सुझाया गया है:

bool b = str.Equals("1");

39
मैं किसी भी रूप को x ? true : falseहास्यप्रद मानता हूं ।
— केंडल फ़्री

5
bool b = str.Equals("1") पहली नज़र में ठीक और अधिक सहज काम करता है।
— एरिक फिलिप्स

@ ErikPhilips इतना सहज नहीं है जब आपका स्ट्रिंग strअशक्त है और आप चाहते हैं कि नल को गलत के रूप में हल किया जाए।
— माइकिटिवे जूल

7

मैंने मोहम्मद सिपाहीवंद की अवधारणा पर कुछ ज्यादा ही विस्तारपूर्वक, पिग्गीबैकिंग किया।

    public static bool ToBoolean(this string s)
    {
        string[] trueStrings = { "1", "y" , "yes" , "true" };
        string[] falseStrings = { "0", "n", "no", "false" };


        if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return true;
        if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return false;

        throw new InvalidCastException("only the following are supported for converting strings to boolean: " 
            + string.Join(",", trueStrings)
            + " and "
            + string.Join(",", falseStrings));
    }

5

मैंने स्ट्रिंग को बूलियन में बदलने के लिए नीचे दिए गए कोड का उपयोग किया।

Convert.ToBoolean(Convert.ToInt32(myString));

यदि केवल दो संभावनाएं "1" और "0" हैं, तो Convert.ToInt32 को कॉल करना अनावश्यक है। यदि आप अन्य मामलों पर विचार करना चाहते हैं, तो var isTrue = Convert.ToBoolean ("true") == true && Convert.ToBoolean ("1"); // दोनों सत्य हैं।
— TamusJRoyce

माइकल फ्रीजिम टिप्पणी पर मोहम्मद सिपाहीवंद का जवाब देखें!
— TamusJRoyce

3

यहाँ मेरा सबसे क्षमाशील स्ट्रिंग बूल रूपांतरण पर प्रयास है जो अभी भी उपयोगी है, मूल रूप से केवल पहले चरित्र को बंद कर रहा है।

public static class StringHelpers
{
    /// <summary>
    /// Convert string to boolean, in a forgiving way.
    /// </summary>
    /// <param name="stringVal">String that should either be "True", "False", "Yes", "No", "T", "F", "Y", "N", "1", "0"</param>
    /// <returns>If the trimmed string is any of the legal values that can be construed as "true", it returns true; False otherwise;</returns>
    public static bool ToBoolFuzzy(this string stringVal)
    {
        string normalizedString = (stringVal?.Trim() ?? "false").ToLowerInvariant();
        bool result = (normalizedString.StartsWith("y") 
            || normalizedString.StartsWith("t")
            || normalizedString.StartsWith("1"));
        return result;
    }
}


1

मैं इसका उपयोग करता हूं:

public static bool ToBoolean(this string input)
        {
            //Account for a string that does not need to be processed
            if (string.IsNullOrEmpty(input))
                return false;

            return (input.Trim().ToLower() == "true") || (input.Trim() == "1");
        }

0

मुझे विस्तार के तरीके पसंद हैं और यह वह है जिसका मैं उपयोग करता हूं ...

static class StringHelpers
{
    public static bool ToBoolean(this String input, out bool output)
    {
        //Set the default return value
        output = false;

        //Account for a string that does not need to be processed
        if (input == null || input.Length < 1)
            return false;

        if ((input.Trim().ToLower() == "true") || (input.Trim() == "1"))
            output = true;
        else if ((input.Trim().ToLower() == "false") || (input.Trim() == "0"))
            output = false;
        else
            return false;

        //Return success
        return true;
    }
}

फिर इसका उपयोग करने के लिए बस कुछ ऐसा करें ...

bool b;
bool myValue;
data = "1";
if (!data.ToBoolean(out b))
  throw new InvalidCastException("Could not cast to bool value from data '" + data + "'.");
else
  myValue = b;  //myValue is True

-1

यदि आप परीक्षण करना चाहते हैं कि क्या कोई स्ट्रिंग बिना किसी फेंके अपवाद के एक वैध बूलियन है तो आप यह कोशिश कर सकते हैं:

    string stringToBool1 = "true";
    string stringToBool2 = "1";
    bool value1;
    if(bool.TryParse(stringToBool1, out value1))
    {
        MessageBox.Show(stringToBool1 + " is Boolean");
    }
    else
    {
        MessageBox.Show(stringToBool1 + " is not Boolean");
    }

उत्पादन is Boolean और stringToBool2 के लिए उत्पादन है: 'बुलियन नहीं है'

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.