C語言常用字符串處理函數

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    //char strArr[100] = "abcdefghigklmn";

    /*函數名: strcpy
    功  能 : 拷貝一個字符串到另一個
    用  法 : char *stpcpy(char *destin, char *source);*/
    char string[10];
    char *str1 = "abcdefghi";
    strcpy_s(string, str1);
    printf("%s\n", string);

    /*函數名: strcat
    功  能 : 字符串拼接函數
    用  法 : char *strcat(char *destin, char *source);*/
    char destination[25];
    char *blank = " ", *c = "C++", *Borland = "Borland";
    strcpy_s(destination, Borland);
    strcat_s(destination, blank);
    strcat_s(destination, c);
    printf("%s\n", destination);

    /*函數名: strchr
    功  能 : 在一個串中查找給定字符的第一個匹配之處
    用  法 : char *strchr(char *str, char c);*/
    const char str[] = "abcdef";
    const char ch = 'c';
    const char *ret;
    ret = strchr(str, ch);
    printf("%c\n", *ret);

    /*函數名: strcmp
    功  能 : 串比較
    用  法 : int strcmp(char *str1, char *str2);
    看Asic碼,str1>str2,返回值 > 0,str1<str2,返回值 < 0;兩串相等,返回0*/
    char *buf1 = "aaa", *buf2 = "bbb", *buf3 = "ccc";
    int ptr;
    ptr = strcmp(buf2, buf1);
    if (ptr > 0)
        printf("buffer 2 is greater than buffer 1\n");
    else
        printf("buffer 2 is less than buffer 1\n");
    ptr = strcmp(buf2, buf3);
    if (ptr < 0)
        printf("buffer 2 is less than buffer 3\n");
    else
        printf("buffer 2 is greater than buffer 3\n");

    /*函數名: strncmpi
    功  能 : 將一個串中的一部分與另一個串比較, 不管大小寫
    用  法 : int strncmpi(char *str1, char *str2, unsigned maxlen);*/
    char *buf11 = "BBB", *buf12 = "bbb";
    int ptr1;
    ptr1 = _strcmpi(buf12, buf11);
    if (ptr1 > 0)
        printf("buffer 2 is greater than buffer 1\n");
    if (ptr1 < 0)
        printf("buffer 2 is less than buffer 1\n");
    if (ptr1 == 0)
        printf("buffer 2 equals buffer 1\n");

    /*函數名: strcpy
    功  能 : 串拷貝
    用  法 : char *strcpy(char *str1, char *str2);*/
    char string1[10];
    char *str111 = "abcdefghi";
    strcpy_s(string1, str111);
    printf("%s\n", string1);

    /*函數名: strrev
    功  能 : 串倒轉
    用  法 : char *strrev(char *str);*/
    char forward[] = "string";//char* forward = "string";不行,因爲是字符串常量
    printf("Before strrev(): %s\n", forward);
    _strrev(forward);
    printf("After strrev():  %s\n", forward);

    /*函數名: strstr
    功  能 : 在串中查找指定字符串的第一次出現
    用  法 : char *strstr(char *str1, char *str2);*/
    char *str133 = "Borland International", *str23 = "nation", *ptr12;
    ptr12 = strstr(str133, str23);
    printf("The substring is: %s\n", ptr12);


    system("pause");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章