31-字符串经典问题

时间:2022-05-22 04:18:25

1、示例1

31-字符串经典问题
buf = hello (nu

31-字符串经典问题

2、示例2

31-字符串经典问题

#include <stdio.h>
#include <string.h>

int main()
{
    #define STR "Hello, \0D.T.Software\0"

    char* src = STR;
    char buf[255] = {0};

    snprintf(buf, sizeof(buf), src);

    printf("strlen(STR) = %d\n", strlen(STR));
    printf("sizeof(STR) = %d\n", sizeof(STR));

    printf("strlen(src) = %d\n", strlen(src));
    printf("sizeof(src) = %d\n", sizeof(src));

    printf("strlen(buf) = %d\n", strlen(buf));
    printf("sizeof(buf) = %d\n", sizeof(buf));

    printf("src = %s\n", src);
    printf("buf = %s\n", buf);

    return 0;
}

strlen(STR) = 7
sizeof(STR) = 22
strlen(src) = 7
sizeof(src) = 8
strlen(buf) = 7
sizeof(buf) = 255
src = Hello, 
buf = Hello, 

31-字符串经典问题

3、示例3

31-字符串经典问题

#include <stdio.h>
#include <string.h>

int main()
{
    #define S1 "D.T.Software"
    #define S2 "D.T.Software"

    if( S1 == S2 )//编译器会将相同的字符串字面来那个映射到同一个无名数组中
    {
        printf("Equal\n");
    }
    else
    {
        printf("Non Equal\n");
    }

    if( strcmp(S1, S2) == 0 )
    {
        printf("Equal\n");
    }
    else
    {
        printf("Non Equal\n");
    }

    return 0;
}

Equal
Equal

31-字符串经典问题

示例4

31-字符串经典问题

#include <stdio.h>
#include <string.h>

void right_shift_r(const char* src, char* result, unsigned int n)
{
    const unsigned int LEN = strlen(src);
    int i = 0;

    for(i=0; i < LEN; i++)
    {
        result[(n + i) % LEN] = src[i];
    }

    result[LEN] = '\0';
}

int main()
{
    char result[255] = {0};

    right_shift_r("abcde", result, 2);

    printf("%s\n", result);

    right_shift_r("abcde", result, 5);

    printf("%s\n", result);

    right_shift_r("abcde", result, 8);

    printf("%s\n", result);

    return 0;
}