leetcode824题,山羊拉丁文
leetcode151题,翻转字符串里的单词
leetcode635题,设计日志存储系统。主要方法是通过/0截断Time的长度,再利用strcmp跟每条记录作比较。
注意malloc一个char之后,初始化的玩法是给A[0]=’\0’;
strcmp两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。相同返回0,如果str1<str2 返回负数,反之正数
如下是几个函数的安全写法(strcat和strcpy都需要有个返回值的,strtok的是非空即可)
1、 char *buff = NULL;
p = strtok_s(s, " ", &buff);
while (p != NULL) {
p= strtok_s(NULL, " ", &buff);
}
2、strcat_s(ret, length + 1, tmp[--i]);
3、strcpy_s(ret, length + 1, a);
4、strcmp(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;
}