摘要:本文主要向大家介绍了JAVA程序实例的字符串处理函数的用法案例,通过具体的内容向大家展示,希望对大家学习JAVA程序实例有所帮助。
本文主要向大家介绍了JAVA程序实例的字符串处理函数的用法案例,通过具体的内容向大家展示,希望对大家学习JAVA程序实例有所帮助。
细节:
1、一定要对地址要加非0断言和const常量。
assert宏的原型定义在<assert.h>中,原型定义:
#include <assert.h>
void assert( int expression );
assert的作用是计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。
2、为了实现链式表达式操作,所以返回目的地址。
例如 int length = strlen( strcpy( strDest, “hello world”) );
3、'\0'和NULL转程整型都是0,但其类型是不同的'\0'是字符,NULL 为(void *)0 是指针。
判断字符串结尾时,用'\0'。判断指针,用NULL。不要混用。
4、如何遍历字符串。另外,一定要注意指针的位置。
代码:
#include<stdio.h> #include<stdlib.h> #include<assert.h> int strlen(const char * str) { assert(str != NULL); int n = 0; while((*str++) != '\0') //while(*str++) ++n; return n; } char *strcpy(char * dst,const char *src) { assert(dst != NULL && src != NULL); char *sdst = dst; //while((*dst++ = *src++) != '\0'); while(*dst++ = *src++); return sdst; } char *strcat(char *dst, const char *src) { assert(dst != NULL && src != NULL); char * sdst = dst; //while(*dst) // dst++; while(*dst++); dst--;//注意‘\0’字符,所以要减去1 //while((*dst++ = *src++) != '\0'); while(*dst++ = *src++); return sdst; } void *memcpy(void *dst,const void *src,size_t n) { assert((dst != NULL) && (src != NULL)); char *pdst = (char *)dst; const char *psrc = (char *)src; while(n--) *pdst++ = *psrc++; return pdst; } void *memmove(void *dst,const void *src,size_t n) { assert((dst != NULL) && (src != NULL)); char *pdst = (char *)dst; const char *psrc = (char *)src; if(pdst + n < psrc || pdst > psrc +n) { //没有内存重叠,从前向后拷贝 while(n--) *pdst++ = *psrc++; } else { //有内存重叠,逆序拷贝 pdst = pdst + n - 1; psrc = psrc + n - 1; while(n--) *pdst-- = *psrc--; } return pdst; } int main() { char p[20] = "tfytest!"; int n = strlen(p); printf("n = %d \n",n); char src[5] = "haha"; char sr[] = "yyy"; //strcpy(p,sr); //printf("%s \n",p); strcat(p,src); printf("strcat test:%s \n",p); memcpy(p,src,sizeof(src)); printf("--------------------------\n memcpy test:%s \n",p); memmove(p,src,sizeof(src)); printf("--------------------------\n memmoves test:%s \n",p); system("pause"); }
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注编程语言JAVA频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号