几个对字符串进行操作的函数

1: char *strcpy(char *to, char *from);

     该函数将串from复制到串to中,并且返回一个指向串to的开始处的指针。

     例如:strcpy(s3,s1);   //s3=“dirtreeformat”

注意:char *s这样定义的字符串是常量,必须定义的时候就初始化,而char s[30]这样定义的字符串是变量,允许对他进行改变

#include <stdio.h>
#include <string.h>
int main()
{
    const char *s = "Golden Global View";
    char s1[30];
    strcpy(s1, s);
    printf("s1 = %s", s1);
    return 0;
}

2:

  char  *strcat(char *to, char *from)

  该函数将串from复制到串to的末尾,并且返回一个指向串to的开始处的指针。

  例如:strcat(s3,”/”)

          strcat(s3,s2);  //s3=“dirtreeformat/test.cpp”

 这个地方需要注意的就是如果是直接串联的话要注意第二个参数是一个字符串,比如strcat(s, " / ");不要忘记双引号

#include <stdio.h>
#include <string.h>
int main()
{
    char s[30] = "Golden Global View";
    strcat(s, " / ");
    char s1[30] = "I am happy!";
    strcat(s, s1);
    printf("s = %s", s);
    return 0;
}

 3:将串s中的第pos个字符开始的连续的len个字符复制到串sub中

看了半天,发现一个问题,这样用的话字符串中不能有空格,不然有时候就会多输出一位字符

void substr(string sub, string s, int pos, int len)

   {

       if(pos<0 || pos>strlen(s)-1 || len<0)

         return ;

       strncpy(sub,s+pos,len);

   }

#include <stdio.h>
#include <string>
#include <string.h>
using namespace std;
void substr(char sub[], char s[], int pos, int len)
{
    if(pos < 0 || pos > int(strlen(s)-1) || len < 0)
        return;
    strncpy(sub, s+pos, len);
}
int main()
{
    char s[30] = "GoldenGlobalView";
    char s1[30];
    //strncpy(s1, s+7, 6);
    substr(s1, s, 7, 3);
    printf("%s
", s1);
    return 0;
}
原文地址:https://www.cnblogs.com/rain-1/p/4963064.html