欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c、c++字符串相关讲解

程序员文章站 2022-06-24 20:13:46
名称:strcpy 功能:复制字符串 char* strcpy(char* dest, const char* src) { if(dest == NULL |...
名称:strcpy

功能:复制字符串

char* strcpy(char* dest, const char* src)
{
    if(dest == NULL || src == NULL)
    {
        return NULL;
    }
    char* tmp = dest;
    while((*tmp++ = *src++) != '\0');
    return dest;
}
名称:strncpy

功能:复制字符串

strncpy把src所指向以'\0'结尾的字符串的前n个字符复制到dest所指的数组中,返回指向dest的指针。

注意:

当n>=sizeof(src)时,拷贝正确,并在dest字符串后面加入'\0';

当n

char* strncpy(char* dest, const char* src, size_t count)
{
    if(dest == NULL || src == NULL)
    {
        return NULL;
    }
    char* tmp = dest;
    while(count--)
    {
        *dest++ = *src++;
    }
    return tmp;
}
名称:strcmp

功能:比较字符串

int strcmp(const char* s0, const char* s1)
{
    int ret = 0;
    unsigned char c1,c2;
    while(1)
    {
        c1 = *s0++;
        c2 = *s1++;
        if(c1 != c2)
        {
            return c1 > c2 ? 1 : -1;
        }
        if(!c1)
        {
            break;
        }
    }
    return ret;
}
名称:strncmp

功能:比较字符串

int strncmp(const char* s0, const char* s1, size_t count)
{
    int ret = 0;
    unsigned char c1,c2;
    while(count)
    {
        c1 = *s0++;
        c2 = *s1++;
        if(c1 != c2)
        {
            return c1 > c2 ? 1 : -1;
        }
        if(!c1)
        {
            break;
        }
        count--;
    }
    return ret;
}
名称:reserve

功能:字符串反转

void reserve(char* word)
{
    if(word != NULL)
    {
        char* start = word;
        char* end = word;
        while(*end++);
        end -= 1;
        while(start < end)
        {
            char s = *start;
            *start = *end;
            *end = s;
            start++;
            end--;
        }
    }
}
名称:reserveWords

功能:字符串反转

I love you -----> you love i

void reserveWords()
{
    char words[] = "I love You";
    reserve(words);
    
    char* start = words;
    char* end = words;
    while(*end != '\0')
    {
        if(*end == '\0' || *end == ' ')
        {
            char tmp[20];
            memcpy(tmp, start, end - start);
            reserve(tmp);
            start = end;
        }
        else if(*end == ' ')
        {
            start++;
            end++;
        }
        else
        {
            end++;
        }
    }
}