算法之指针方法求字符串长度简单实现

此处主要帮助了解指针的使用。这里指针指示字符数组第一个字符的位置

//用指针的方法求字符串的长度
//展示指针的简单使用 
#include<iostream>
using namespace std;

//指针方法求字符长度 
int strlen(char* s)
{
    int i = 0;
    while (*s!='\0')
    {
        ++i;
        ++s;
    }

    return i;
}
//字符数组的方法求字符串长度 
int strlen2(char s[])
{
    int i=0;
    while(s[i]!='\0')
    {
        ++i;
    }
    return i;
} 

int main()
{
    char str[100];
    int len=0,len2=0;
    cout<<"please input your string:";
    cin>>str;

    len = strlen(str);
    len2=strlen2(str);

    cout<<"the length is : " <<len<<endl;

    cout<<"not pointer the length:"<<len2<<endl;
}

猜你喜欢

转载自blog.csdn.net/vincent_yuan1991/article/details/80220202