如何检查字符串仅包含一和零?

时间:2019-03-27 10:12:10

标签: c

我正在尝试检测字符串是否仅包含字符“ 0”和“ 1”。这是我到目前为止的内容:

    while (indexCheck < 32) {

        if ((input[indexCheck] != '0') && (input[indexCheck] != '1')) {

            printf("not binary ");
            indexCheck++;

        }  else if ((input[indexCheck] = '0') && (input[indexCheck] = '1')) {
            indexCheck++;
            printf("is binary ");

        } 

    }

我知道为什么数组中的每个字符都返回“ is binary”或“ not binary”,但是我不知道如何解决。如果字符串仅由“ 1”和“ 0”组成,我希望它返回“是二进制的”一次;如果为false,则相反。我是C语言的新手,所以感谢所有帮助。

6 个答案:

答案 0 :(得分:12)

您可以通过检查strspn()是否返回字符串的长度(通过查看它返回的值的索引是否为0)来查看它是否仅包含某些字符,而不是手动遍历该字符串。字符串末尾的终止符):

_Bool is_binary(const char *s) {
  if (!s || !*s) {
    return 0;
  }
  return s[strspn(s, "01")] == '\0';
}

答案 1 :(得分:9)

我为此做一个函数:

int isBinary(const char *input)
{
    for (int i = 0; input[i]; ++i)
        if (input[i] != '0' && input[i] != '1')
            return 0;
    return 1;
}

然后您可以调用该函数:

if (isBinary("0001110110101"))
    printf("is binary\n");
else
    printf("is not binary\n");

https://ideone.com/tKBCbf

答案 2 :(得分:2)

找到一个既不是'0'也不是'1'的字符时,可以停止在字符串中循环。循环终止后,请检查是否已到达字符串的末尾,即当前字符为空字符package com.punjabweb.myapp2 import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.Button import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import kotlinx.android.synthetic.main.activity_login.* class LoginActivity : AppCompatActivity() { //Firebase references private var mAuth: FirebaseAuth? = null // FirebaseApp.initializeApp(this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) val loginBtn = findViewById<View>(R.id.btnLogin) as Button loginBtn.setOnClickListener { loginUser() } } private fun loginUser() { mAuth = FirebaseAuth.getInstance() val email = etEmail?.text.toString() val password = etPassword?.text.toString() if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password)) { Toast.makeText(this, "Enter all details", Toast.LENGTH_SHORT).show() } else { mAuth!!.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with signed-in user's information var firebasUser = FirebaseAuth.getInstance().currentUser!! // updateUI() } else { // If sign in fails, display a message to the user. Toast.makeText( this@LoginActivity, "Authentication failed.", Toast.LENGTH_SHORT ).show() } } } fun updateUI() { val intent = Intent(this@LoginActivity, MainActivity::class.java) // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } } }

'\0'

答案 3 :(得分:1)

您可以这样做:

while (indexCheck < 32) 
{
    if ((input[indexCheck] != '0') && (input[indexCheck] != '1'))
    {
        break;
    }
    else
    {
        indexCheck++;
    } 
}
if (indexCheck == 32)
    printf("is binary ");
else
    printf("is not binary ");

仅当它处理完所有元素并且未遇到非1或0时,才以indexCheck == 32结束循环,因此您可以使用它来确定要打印的内容。

请注意,您不需要else的条件。

答案 4 :(得分:1)

    int isBinary = 1;
    while (input[indexCheck] != '\0')
    {
        if (input[indexCheck] != '1' && input[indexCheck] != '0')
        {
            isBinary = 0;
            break;
        }
        ++indexCheck;
    }
    if (isBinary)
    {
        printf("binary");
    }
    else
    {
        printf("not binary");
    }

检查字符串input中的每个元素。如果input[index]不是01,则标志isBinary变为0并中断while。而且您不需要字符串的长度。

答案 5 :(得分:1)

有一段代码为您提供注释。

#include <stdio.h>
#include <stdlib.h>

#define STRING_SIZE 32 // Better to use #define for reusability

// Function prototype
int isBinary(char * testInput);

// Main program
int main(void)
{
    // Test inputs
    char testInputBinary[33] = "01010101010101010101010101010101";
    char testInputNotBinary[33] = "010101010101010101010101010101ab";

    // Test & collect results
    if (isBinary(testInputBinary))
    {
        printf("Binary ! \n");
    }
    else
    {
        printf("Not binary ! \n");
    }


    if (isBinary(testInputNotBinary))
    {
        printf("Binary ! \n");
    }
    else
    {
        printf("Not binary ! \n");
    }

    return EXIT_SUCCESS;
}

int isBinary(char * testInput)
{
    int loopIdx = 0; // Loop index
    int returnVal = 0; // 0: False, 1: True

    // iterate over string
    for (loopIdx = 0; loopIdx < STRING_SIZE; loopIdx++)
    {
        if(testInput[loopIdx] != '0' && testInput[loopIdx] != '1')
        {
            break;
        }
    }

    // If the loop is not broken, it means all characters are in binary form
    if (loopIdx == STRING_SIZE)
    {
        returnVal = 1;
    } // No need to writing else clause since returnVal = 0 at the beginning

    return returnVal;
}