Reputation: 195
Does anyone have an idea how to check for one's or zeros in a Bitstring? The below code checks for ones and zeros in a string, but I would like to add an extension bitstring that does the same thing. This way, I can use the method on the bitstring itself with out having to first evaluate the string.
Currently, I have to check before I entered the bitstring method.
string MustBeBitsInStringOnesOrZeros = "11001";
bool boTesting = Is1Or0(MustBeBitsInStringOnesOrZeros);
// I would like to add an extension to check for ones and zeros
// Example: MustBeBitsInStringOnesOrZeros.Is1Or0();
if (boTesting == true)
{
Bitstring a = new Bitstring(MustBeBitsInStringOnesOrZeros);
}
else
{
string b = MustBeBitsInStringOnesOrZeros;
}
private static bool Is1Or0(string stringBit)
{
// This function check each
// character in a string for "1"
// or "0".
bool results = false;
for (int i = 0; i < stringBit.Length; i++)
{
var x = stringBit[i];
if (x == '1' || x == '0')
{
results = true;
}
else
{
results = false;
break;
}
}
return results;
}
=== Modified to show results of Bassie's example from a sealed class.
Bassie,
Well, what I was trying to say was that I cannot place the method in the sealed class with the keyword 'this' in the method. So I created another class but, I have to use it a different way and I wanted to use it the way you call it.
//I have to use it this way:
Bitstring OnesAndZeroCheck = new Bitstring(); // Bitstring is in a sealed class
Boolean g = OnesAndZeroCheck.IsBitstring2("1100111100011100101010101010101101010101010"); // Is in the sealed class
//but want to call it this way:
var successInput = "1101";
successInput.Is1Or0(); // true
Upvotes: 2
Views: 91
Reputation: 70
tested in video.
public static bool isBitstring(string s)
{
foreach (char c in s)
{
if (!(c >= '0' && c <= '1')) {
return false;
}
}
return true;
}
string str = "100000011100101010010101";
if (isBitstring(str))
{
Console.WriteLine("is Bitstring");
}
else
{
Console.WriteLine("is not Bitstring");
}
Upvotes: 1
Reputation: 10390
If I understand you correctly, you could define your extension method like this
public static class StringExtensions
{
public static bool Is1Or0(this string stringBit)
=> stringBit.All(c => c == '1' || c == '0');
}
And call with
var successInput = "1101";
successInput.Is1Or0(); // true
var failureInput = "1121"
failureInput.Is1Or0(); // false
From MSDN Enumerable.All:
Determines whether all elements of a sequence satisfy a condition.
This works because a string is actually just an IEnumerable
of char
- so when we call the IEnumerable.All()
extension method, we check the condition against each individual char in the string
Note you will need to include using System.Linq;
to your file that contains the extension method
Upvotes: 4