字符串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; |
|