zoukankan      html  css  js  c++  java
  • 字符串拷贝问题

    问题:把源字符串拷贝到目的字符串,如果指定关键字,则以该关键字结束(不包括关键字本身),如果拷贝失败,则得到空串。
    具体要求:实现如下函数原型SafeStrcpy2KeyWord(),并在代码中调用该函数实现上述功能。该函数的实现要考虑各种可能的参数取值,以确保程序不出现崩溃。

    int SafeStrcpy2KeyWord(char* pDestBuffer,    //拷贝的目的地地址

                   char* pSourceString,    //拷贝的源地址

                   int nDestBufferSize,    //拷贝的目的地缓冲区长度

                   char* szKeyWord);    //指定关键字符串


    返回值:所拷贝的字符串长度。如果拷贝失败,则返回0。

    Input
    输入包含多组数据,以EOF结束
    每组数据第一行为不含空格的源字符串,长度小于256;接下来的一行或多行都是关键字串(长度小于16),一直到END结束。“NULL”表示关键字串为空,此时输出的拷贝后的长度应为0,拷贝后的字符串为空串(也用”NULL”表示,见下文)。

    Output
    对于每组数据输出拷贝的长度和拷贝后的目的字符串,以空格分隔。如果该目的字符串为空,则用”NULL”表示。

    Sample Input
    /home/tony/work_server/1/rtest/relayer.out
    /
    /t
    /1/r
    .
    NULL
    END

    Sample Output
    0 NULL
    5 /home
    22 /home/tony/work_server
    38 /home/tony/work_server/1/rtest/relayer
    0 NULL

    回答:

    #include <iostream>
    #include <string>
    using namespace std;
    int SafeStrcpy2KeyWord(char* pDestBuffer, //拷贝的目的地地址
             char* pSourceString, //拷贝的源地址
             int nDestBufferSize, //拷贝的目的地缓冲区长度
             char* szKeyWord); //指定关键字符串

    int main() {
     freopen("in","r",stdin);
     char s1[300],s2[300],s3[300];
     int len;
     while(scanf("%s",s1) !=EOF)
     {
      while(scanf("%s",s2) && strcmp(s2,"END") != 0)
      {
       len = SafeStrcpy2KeyWord(s3,s1,300,s2);
       if(len == 0)
        printf("0 NULL/n");
       else
        printf("%d %s/n",len,s3);
      }
     }
     return 0;
    }


    int SafeStrcpy2KeyWord(char* pDestBuffer, //拷贝的目的地地址
             char* pSourceString, //拷贝的源地址
             int nDestBufferSize, //拷贝的目的地缓冲区长度
             char* szKeyWord) //指定关键字符串

    {
     if(nDestBufferSize == 0 || strcmp(szKeyWord,"NULL") == 0)
     {
      return 0;
     }
     char *k = strstr(pSourceString,szKeyWord);
     if(k == NULL)
     {
      strcpy(pDestBuffer,pSourceString);
      return strlen(pSourceString);
     }
     if(k-pSourceString==0|| k-pSourceString > nDestBufferSize)
     {
      return 0;
     }
     int i;
     for(i = 0;i < k-pSourceString; i++)
     {
      pDestBuffer[i] = pSourceString[i];
     }
     pDestBuffer[i] = 0;
     return i ;
    }

  • 相关阅读:
    正经学C#_循环[do while,while,for]:[c#入门经典]
    Vs 控件错位 右侧资源管理器文件夹点击也不管用,显示异常
    asp.net core 获取当前请求的url
    在实体对象中访问导航属性里的属性值出现异常“There is already an open DataReader associated with this Command which must be
    用orchard core和asp.net core 3.0 快速搭建博客,解决iis 部署https无法登录后台问题
    System.Data.Entity.Core.EntityCommandExecution The data reader is incompatible with the specified
    初探Java设计模式3:行为型模式(策略,观察者等)
    MySQL教程77-CROSS JOIN 交叉连接
    MySQL教程76-HAVING 过滤分组
    MySQL教程75-使用GROUP BY分组查询
  • 原文地址:https://www.cnblogs.com/benchao/p/4513571.html
Copyright © 2011-2022 走看看