分享

C学习心得

 东在南方 2014-03-16
字符串char *str1="aaaabbbbccccbbbb";char *str2="bbbb";
不使用库函数实现字符串的一部分操作:
1.求字符串的长度:
    第一种方法:while(*(str1++)) str_len++;
    第二种方法:for(int i=0,*(str1+i)!='\0';i++) str_len++;
2.求子串在主串。
    int i=0;int j=0;
    while(*(str1+i))
    {
if(*(str1+i)==*(str2+j))
{
i++;j++;
}
else
{
i++;j=0;
}
if(*(str2+j)=='\0')
{
return i-j;
//break; //注释掉的话可以返回多个字符的位置。
}
    }
3.判断是否相等。
while(*(str1+i)!='\0'&&*(str2+i)!='\0')
{
if(*(str1+i)==*(str2+i))
i++;
else 
{
cout<<"they are not compared"<<endl;
break;
}
}
if(*(str1+i)=='\0'||*(str2+i)=='\0')
cout<<"they are not compared"<<endl;
4.合并字符串。合并字符串的时候一定要先为之分配足够的内存空间,否则便会出现内存越界的情况。
  while(*(str1+i))
{
i++;
str1_len++;
}
while(*(str2++))
str1_len++;
char *s=(char *)malloc (str1_len);
s=str1;
cout<<"the string before copy is:"<<s<<endl;
int j=0;
while(*(str2+j))
{
*(s+j)=*(str2+j);
j++;
}
cout<<"the string after copy is:"<<s<<endl;
cout<<"the length of  string after copy is:"<<str1_len<<endl; 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多