C语言字符串操作

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main01()
{
    
    char str1[] = { 'a', 'b' }; //一直读取到\0
    printf("%s\n", str1);

    char str3[] = "hello";
    printf("%s\n", str3);
    printf("sizeof str:%d\n", sizeof(str3)); //包括\n 6
    printf("strlen str:%d\n", strlen(str3)); //不包括\n 5

    char str4[100] = "hello";
    printf("%s\n", str4);
    printf("sizeof str:%d\n", sizeof(str4)); //包括\n 100
    printf("strlen str:%d\n", strlen(str4)); //不包括\n 5

    char str5[] = "hello\0world";
    printf("%s\n", str5);
    printf("sizeof str:%d\n", sizeof(str5)); //包括\n 12
    printf("strlen str:%d\n", strlen(str5)); //不包括\n 5

    //八进制12 10进制10 ascii  为 换行
    char str6[] = "hello\012world";
    printf("%s\n", str6);
    printf("sizeof str:%d\n", sizeof(str6)); //包括\n 12
    printf("strlen str:%d\n", strlen(str6)); //不包括\n 11     
    system("pause");
}
//字符串拷贝
void copyString01(char * dest, char * source)
{
    int len = strlen(source);
    for (int i = 0; i < len; i++)
    {
        dest[i] = source[i];
    }
    dest[len] = '\0';
}
void copyString02(char * dest, char * source)
{
    while (*source != '\0')
    {
        *dest = *source;
        dest++;
        source++;
    }
    *dest = '\0';

}
void copyString03(char * dest, char * source)
{
    while (*dest++ = *source++){}
}
void test02()
{
    char * str = "hellow world";
    char * str2 = "see";
    char * str3 = "Gabriel";
    char buff[1024];
    copyString01(buff, str);
    printf("%s\n", buff);
    copyString02(buff, str2);
    printf("%s\n", buff);
    copyString03(buff, str3);
    printf("%s\n", buff);
}

//字符串反转
void reverString(char * str)
{
    int len = strlen(str);
    char * start = str;
    char * end = str + len - 1;
    while (start < end)
    {
        char temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }
}

void test()
{
    char str[] = "abcdefg";
    reverString(str);
    printf("%s", str);
}

 

void main()
{
    test02();
    system("pause");
}

 

posted @ 2018-07-25 16:06  LifeOverflow  阅读(235)  评论(0)    收藏  举报