如何在C++中计算C_String中的字符数?

问题描述 投票:0回答:1

我是一名计算机科学专业的新学生,我有一个家庭作业问题如下:

编写一个传入 C 字符串的函数,并使用指针确定字符串中的字符数。

这是我的代码:

#include <iostream>
#include <string.h>
using namespace std;
const int SIZE = 40;

int function(const char* , int, int);

int main()
{
     char thing[SIZE];
     int chars = 0;

     cout << "enter string. max " << SIZE - 1 << " characters" << endl;
     cin.getline(thing, SIZE);
     int y = function(thing, chars, SIZE);
     cout << y;
}


int function(const char *ptr, int a, int b){
    a = 0;
    for (int i = 0; i < b; i++){
        while (*ptr != '\0'){
            a++;
        }
    }
    return a;
}
c++ function for-loop while-loop c-strings
1个回答
1
投票

我认为你正在尝试在这里重写

strlen()
函数。尝试查看以下链接查找指针指向的字符串的大小。 简而言之,您可以使用
strlen()
函数来查找字符串的长度。您的函数的代码将如下所示:

int function(const char *ptr) 
{
    size_t length = strlen(ptr);
    return length;
}

你也应该只需要这个函数和main。

编辑:也许我误解了你的问题,你毕竟应该重新发明

strlen()
。在这种情况下,你可以这样做:

unsigned int my_strlen(const char *p)
{
    unsigned int count = 0;

    while(*p != '\0') 
    {
        count++;
        p++;
    }
    return count;
}

这里我将

*p
'\0'
进行比较,因为
'\0'
是空终止符。

这取自https://overiq.com/c-programming-101/the-strlen-function-in-c/

© www.soinside.com 2019 - 2024. All rights reserved.