C数据结构-字符串操作

leetcode824题,山羊拉丁文
leetcode151题,翻转字符串里的单词
leetcode635题,设计日志存储系统。主要方法是通过/0截断Time的长度,再利用strcmp跟每条记录作比较。
注意malloc一个char之后,初始化的玩法是给A[0]=’\0’;

strcmp两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。相同返回0,如果str1<str2 返回负数,反之正数
在这里插入图片描述
如下是几个函数的安全写法(strcat和strcpy都需要有个返回值的,strtok的是非空即可)

1char *buff = NULL;
	p = strtok_s(s, " ", &buff);
	while (p != NULL) {
		p= strtok_s(NULL, " ", &buff);
	}
2strcat_s(ret, length + 1, tmp[--i]);
3strcpy_s(ret, length + 1, a);
4strcmp(str1, str2) == 0 

如下是对比安全函数和不安全函数的写法
1、strtok函数,注意s不能是常量
分割字符串,依赖while循环获取全部参数。

//leetcode通过写法
char *p = strtok(s, " ");
if (p == NULL) return "";
while (p != NULL) {
    tmp[i++] = p;
	p = strtok(NULL, " ");
}
//安全函数对比
char *buff;
tmp[i] = strtok_s(s, " ", &buff);
while (tmp[i] != NULL) {
	i++;
	tmp[i] = strtok_s(NULL, " ", &buff);
}

2、strcat函数 注意,ret未被赋值的时候不能strcat,且leetcode当前写法要判断参数2是否为空

//leetcode通过写法
strcat(ret, " ");
if (tmp[i] == NULL)  break;
strcat(ret, tmp[i]);
//安全函数对比
strcat_s(ret, length + 1, " ");
strcat_s(ret, length + 1, tmp[--i]);

3、strcpy函数 注意,ret要赋初值才能进行运算否则会报错,且leetcode当前写法要判断参数2是否为空

//leetcode通过写法
if (tmp[i-1] != NULL){
    strcpy(ret, tmp[i-1]);
    i--;
}
//安全函数对比
strcpy_s(ret, length + 1, a);

下面是824答案

#include<string.h>
#include<stdio.h>
int main(void)
{
    char input[16]="abc,d";
    char*p;
    /*strtok places a NULL terminator
    infront of the token,if found*/
    p=strtok(input,",");
    if(p)
        printf("%s\n",p);
        /*Asecond call to strtok using a NULL
        as the first parameter returns a pointer
        to the character following the token*/
    p=strtok(NULL,",");
    if(p)
        printf("%s\n",p);
    return 0;
}

山羊代码如下:

char * toGoatLatin(char * S){
    char *result = (char*)malloc(sizeof(char) * 153);
    memset(result, 0, 153);
    char *head = strtok(S, " ");
    int i, cnt = 0;
    int flag = 0;
    while(head != NULL) 
    {
        if (flag == 1) {
            strcat(result, " ");
        }
        flag = 1;
        if (head[0] != 'a' && head[0] != 'e'&& head[0] != 'i'&& head[0] != 'o'&& head[0] != 'a' && head[0] != 'A' && head[0] != 'E'&& head[0] != 'I'&& head[0] != 'O'&& head[0] != 'U' ) {
            char head0[2] = {head[0],0};
            char *head1 = ++head;
            strcat(result, head1);
            strcat(result, head0);
        } else {
            strcat(result,head);
        }
        cnt++;
        strcat(result,"ma");
        for (i = 0; i < cnt; i++) {
            strcat(result,"a");
        }
        head = strtok(NULL," ");
    }
    return result;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值