判断字符串的俩种方法
一:
int my_strlen(char* str)
{
assert(str != nullptr);
int i = 0;
while ('\0' != str[i])
{
i++;
}
return i;
}
int main()
{
char stra[30] = { "yhping" };
int len = my_strlen(stra);
printf("%d \n", len);
return 0;
}
二:利用指针相减
int my_strlen(char* str)
{
assert(str != nullptr);
int *ar = str;
while ('\0' != *ar)
{
ar++;
}
return (int)(ar - str);
}
int main()
{
char stra[30] = { "yhping" };
int len = my_strlen(stra);
return 0;
}
拷贝函数
一:
void my_strcpy(char* dest, const char* src)
{
assert(src != nullptr && dest != nullptr);
while ('\0' != *src)
{
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}
int main()
{
char stra[30] = { "yhping" };
char strb[30] = {};
char strc[30] = {};
my_strcpy(strb, stra);
printf("%s %s \n", stra, strb);
return 0;
}
二:
void my_strcpy(char* dest, const char* src)
{
assert(src != nullptr && dest != nullptr);
int i = 0;
while ('\0' != src[i])
{
dest[i] = src[i]
i++;
}
dest[i] = '\0';
}
int main()
{
char stra[30] = { "yhping" };
char strb[30] = {};
char strc[30] = {};
my_strcpy(strb, stra);
printf("%s %s \n", stra, strb);
return 0;
}
逆置函数
一:
void Print_Array(int* ar,int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d ", ar[i]);
}
}
void ResArray(int* br, int left, int right)
{
assert(br != nullptr && left <= right);
int *p = &br[left];
int *ip = &br[right];
int tmp;
while (p < ip)
{
tmp = *p;
*p = *ip;
*ip = tmp;
p++;
ip--;
}
}
int main()
{
const int n = 10;
int ar[n] = { 12,23,34,45,56,67,78,89,90,100 };
ResArray(ar, 0, 9);
Print_Array(ar, n);
}
二:
void Swap_Int(int* ap, int* bp)
{
assert(ap != nullptr && bp != nullptr);
int tmp = 0;
tmp = *ap;
*ap = *bp;
*bp = tmp;
}
void ResArray(int* br, int left, int right)
{
assert(br != nullptr && left <= right);
if (left < right)
{
Swap_Int(&br[left], &br[right]);
left++;
right++;
}
}
void类型拷贝
void my_memcpy(void* dest, void* src, unsigned int size)
{
assert(dest != nullptr && src != nullptr && size > 0);
char* cdest = (char*)dest;
char* csrc = (char*)src;
for (int i = 0; i < size;i++)
{
cdest[i] = csrc[i];
}
}
int main()
{
const int n = 10;
int ar[n] = { 12,23,34,45,56,67,78,89,90,100 };
int br[n] = {};
double da[n] = { 1.2,2.,3.4,4.5,5.6,6.7,7.8,8.9,9.0,1.00 };
double db[n] = {};
my_memcpy(br, ar, sizeof(ar));
my_memcpy(db, da, sizeof(da));
return 0;
}