检查字符数组是否只包含 ‘\0’。

huangapple go评论86阅读模式
英文:

Check if char array has just '\0'

问题

我试图做一些大学作业,在这个问题中,我必须确保一个人的全名不是像“        ”这样的全是空格,也没有数字,比如“R4lph 123”。

数字部分我可以处理,但是空格的部分我卡住了。

如果只有一个空格,它可以工作,但是如果是多个空格,它就会停止工作。

int checkName(char* name)
{
    if (name[0] == '
我试图做一些大学作业,在这个问题中,我必须确保一个人的全名不是像“        ”这样的全是空格,也没有数字,比如“R4lph 123”。

数字部分我可以处理,但是空格的部分我卡住了。

如果只有一个空格,它可以工作,但是如果是多个空格,它就会停止工作。

int checkName(char* name)
{
    if (name[0] == '\0') //检查名字是否以“空格”开头。如果是,它是一个无效的名字。
        return 1;
    else
    {
        for (int i = 0; i < strlen(name); i++)
        {
            if (isdigit(name[i])) //检查名字中是否有数字。如果有,它是一个无效的名字。
                return 1;
        }
        return 0;
    }
}

我尝试过多个函数,比如empty()blank(),尽管我无法让blank()在我的代码中工作。
'
) //检查名字是否以“空格”开头。如果是,它是一个无效的名字。
return 1; else { for (int i = 0; i < strlen(name); i++) { if (isdigit(name[i])) //检查名字中是否有数字。如果有,它是一个无效的名字。 return 1; } return 0; } } 我尝试过多个函数,比如empty()blank(),尽管我无法让blank()在我的代码中工作。
英文:

I'm trying to make some college stuff, and in this problem I have to make sure that a full name of a person is not all empty spaces like " " and does not have a number in it like "R4lph 123".
The number part I'm ok, but the empty spaces one is where I'm stuck.
It works if it's only one empty space, but if multiples, it spots working.

int checkName(char* name)
{
    if (name[0] == &#39;
int checkName(char* name)
{
if (name[0] == &#39;\0&#39;) //Checks if name starts with &quot;space&quot;. If so, it&#39;s an invalid name.
return 1;
else
{
for (int i = 0; i &lt; strlen(name); i++)
{
if (isdigit(name[i])) //Checks if there&#39;s a number in the name. If so, it&#39;s an invalid name.
return 1;
}
return 0;
}
}
&#39;) //Checks if name starts with &quot;space&quot;. If so, it&#39;s an invalid name. return 1; else { for (int i = 0; i &lt; strlen(name); i++) { if (isdigit(name[i])) //Checks if there&#39;s a number in the name. If so, it&#39;s an invalid name. return 1; } return 0; } }

I've tried multiple functions like empty() and blank(), although I couldn't make black() work in my code.

答案1

得分: 1

你的想法是正确的,但你没有检查空格,而是检查了不同的字符。我已经将字符串长度的计算移到循环外部,这样我们不会在每次迭代中计算它。

int checkName(char* name)
{
    if (name[0] == ' ') //检查名字是否以空格开头。如果是,那么它是无效的名字。
        return 1;
    else
    {
        int len = strlen(name);
        for (int i = 1; i < len; i++)
        {
            if (isdigit(name[i])) //检查名字中是否有数字。如果是,那么它是无效的名字。
                return 1;
        }
        return 0;
    }
}
英文:

Your idea was correct, but you did not check for space, but a different character. I have moved out the computation for the length of the string so we don't compute it in each iteration.

int checkName(char* name)
{
    if (name[0] == &#39; &#39;) //Checks if name starts with &quot;space&quot;. If so, it&#39;s an invalid name.
        return 1;
    else
    {
        int len = strlen(name);
        for (int i = 1; i &lt; len; i++)
        {
            if (isdigit(name[i])) //Checks if there&#39;s a number in the name. If so, it&#39;s an invalid name.
                return 1;
        }
        return 0;
    }
}

答案2

得分: 0

由于代码部分不需要翻译,请查看以下翻译好的内容:

"Since C++ is tagged here your answer is in the string library, as @pm100 mentioned. The code posted is the C way of C++ programming, which is generally not desired. C++ offers many libraries that will help you 90% of the time.

I changed the prototype so gets a const std::string as a parameter, and made its return type bool. You can change that back to int and remove std::boolalpha in main().

I don't know your professor's requirements since you haven't listed any, so feel free to do anything you want with this code (using a char array vs a string).

The function uses a range-based for-loop to iterate over the string and check if each character is either a digit or a space, if it finds one it throws a runtime error. I used a try-catch block to handle them gracefully but it might be deemed unnecessary. The function returns false if the name is invalid and vice versa."

请注意,代码部分未被翻译。如果您需要进一步的翻译或解释,请告诉我。

英文:

Since C++ is tagged here your answer is in the string library, as @pm100 mentioned. The code posted is the C way of C++ programming, which is generally not desired. C++ offers many libraries that will help you 90% of the time.

I changed the prototype so gets a const std::string as a parameter, and made its return type bool. You can change that back to int and remove std::boolalpha in main().

I don't know your professor's requirements since you haven't listed any, so feel free to do anything you want with this code (using a char array vs a string).

The function uses a range-based for-loop to iterate over the string and check if each character is either a digit or a space, if it finds one it throws a runtime error. I used a try-catch block to handle them gracefully but it might be deemed unnecessary. The function returns false if the name is invalid and vice versa.

#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;stdexcept&gt;

bool checkName(const std::string name) {
    try {
        for (auto letter : name) {
            if (letter == &#39; &#39;) {
                throw std::runtime_error(&quot;[invalid name]&quot;);
            } else if (isdigit(letter)) {
                throw std::runtime_error(&quot;[invalid name]&quot;);
            }
        }
    } catch (std::exception&amp; e) {
        std::cout &lt;&lt; &quot;{error}: &quot; &lt;&lt; e.what() &lt;&lt; std::endl;
        return false;
    }
    return true;
}

int main() {
    const std::string name1 = &quot;John&quot;;
    const std::string name2 = &quot;Jo hn&quot;;
    const std::string name3 = &quot;Jo3hn&quot;;

    std::cout &lt;&lt; std::boolalpha &lt;&lt; checkName(name1) &lt;&lt; &quot;\n&quot;;
    std::cout &lt;&lt; std::boolalpha &lt;&lt; checkName(name2) &lt;&lt; &quot;\n&quot;;
    std::cout &lt;&lt; std::boolalpha &lt;&lt; checkName(name3) &lt;&lt; &quot;\n&quot;;

    return 0;
}

答案3

得分: 0

如果名称只能包含字母字符,您可以使用isalpha方法遍历字符串 - 该方法检查给定字符是否是字母字符。

循环将在以下情况下结束:

  1. 它达到字符串的末尾,因为它只包含有效字符;
  2. 字符串包含一个非有效字符。
int checkName(const char* name)
{
    int number_char = strlen(name);
    if(number_char==0) return 1;
    int index=0;
    while(isalpha(name[index]) && index<number_char) index++;
    return (index==number_char?0:1);
}
英文:

If the the name must contains only alphabetic character, you can itereate through the string using the isalpha method - which check if a given char is an alhpabetic letter or not.

The loop will end when:

  1. it reaches the end of the string because it contains only valid character;

  2. the string contains a non-valid character.

    int checkName(const char* name)
    {
        int number_char = strlen(name);
        if(number_char==0) return 1;
        int index=0;
        while(isalpha(name[index]) &amp;&amp; index&lt;number_char) index++;
        return (index==number_char?0:1);
    }
    

答案4

得分: 0

以下是代码的翻译部分:

在当前的C++中,没有指针的情况下,代码看起来像这样:

#include <cctype>
#include <cassert>
#include <string_view>

// 如果某物只能有两个值,考虑使用bool
// string_view接受许多字符串类型
// 我们可以使用视图,因为我们只检查一个字符串
bool checkName(const std::string_view name)
{
    if (name.size() != 0ul)
    {
        // 基于范围的for循环不会超出范围
        for (const auto c : name)
        {
            if (std::isdigit(c))
            {
                return true;
            }
        }
    }

    return false;
}

int main()
{
    auto nok = checkName("");
    assert(!nok);

    auto ok = checkName("hello1");
    assert(ok);

    return 0;
}

希望这对您有所帮助!

英文:

In current C++, without pointers, the code would look like this:

#include &lt;cctype&gt;
#include &lt;cassert&gt;
#include &lt;string_view&gt;

// if something can have only two values consider using bool
// string_view accepts a lot of string types
// and we can use a view since we are only checking a string
bool checkName(const std::string_view name)
{
    if (name.size() != 0ul)
    {
        // range based for loop cannot go out of scope
        for (const auto c : name)
        {
            if (std::isdigit(c))
            {
                return true;
            }
        }
    }

    return false;
}

int main()
{
    auto nok = checkName(&quot;&quot;);
    assert(!nok);

    auto ok = checkName(&quot;hello1&quot;);
    assert(ok);

    return 0;
}

答案5

得分: 0

在C++中,假设您使用C++,以null结尾的字符数组是C遗留物。我们尽量避免使用它们。替代方案是使用std::string来处理可变字符串,以及std::string_view引用不可变字符串。在您的示例中,后者更好。接下来,建议使用std::isalpha而不是std::isdigit,因为这是您需要的。我使用了非常现代的C++20:

#include <ranges>
#include <cctype>
#include <string_view>

bool checkName(const std::string_view name){
   constexpr auto to_uint = [](auto c)
   {return static_cast<uint8_t>(c);};
   if (auto space=std::ranges::count_if(name, std::isspace, to_uint); (space > 2) || (space == 0) )
       return false;
   return (std::ranges::end(name) ==
           std::ranges::find_if_not(name, [](auto c)
              { return std::isalpha(c)||std::isspace(c); }, to_uint);
};

此函数检查输入字符串是否有一个或两个空格(对应于名字+[中间名字+]姓氏)。然后,如果找到非字母字符,它会返回false。to_uint是一个投影函数,用于防止由于整数提升而引起的意外。

这个实现的问题是它不能检测到两个连续的空格或空输入字符串。这个问题可以通过进一步复杂化来解决,但我没有尝试包含这些复杂性。

英文:

Assuming you use C++, null-terminated character arrays are relics from C legacy. We try to avoid them where possible. Alternatives are std::string for flexible strings and std::string_view for referencing immutable strings. In your example, the later is better. Next thing is to use std::isalfha instead of std::isdigit, because that's what you need. I am going extremely modern, using C++20:

#include &lt;ranges&gt;
#include &lt;cctype&gt;
#include &lt;string_view&gt;

bool checkName(const std::string_view name){
   constexpr auto to_uint = [](auto c)
   {return static_cast&lt;uint8_t&gt;(c);};
   if (auto space=std::ranges::count_if(name, std::isspace, to_uint); (space &gt; 2) || (space == 0) )
       return false;
   return (std::ranges::end(name) ==
           std::ranges::find_if_not(name, [](auto c)
              { return std::isalpha(c)||std::isspace(c); }, to_uint);
};

assert((checkName(&quot;xxx yyy zzz&quot;)));

This function checks if the input string has one or two spaces(corresponding to first+[middle+]last name). Then if a none-alphabetic character is found, returns false. to_uint is a projection function used to prevent surprises due to integer promotions.
The problem with this implementation is that it cannot detect two consecutive spases, or empty input strings. That can also be solved by further complications that I did not try to include.

huangapple
  • 本文由 发表于 2023年6月12日 08:17:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定