字符串翻转
#include "iostream"
using namespace std;
void reverseString(char *str)
{
if (NULL == str)
{
return;
}
int len = strlen(str);
cout << "len====" << len << endl;
#if 0
int start = 0;
int end = len - 1;
while (start < end)
{
char temp = str[start];
str[start] = str[end];
str[end] = temp;
++start;
--end;
}
#else
char *pStart = str;
char *pEnd = str + len - 1;
while (pStart < pEnd)
{
char temp = *pStart;
*pStart = *pEnd;
*pEnd = temp;
++pStart;
--pEnd;
}
#endif
}
//2. 字符串反转
void test03()
{
char p[] = "abc";
reverseString(p);
cout << "p====" << p << endl;
}
int main()
{
test03();
system("pause");
return EXIT_SUCCESS;
}
字符串复制
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void test01()
{
char str1[] = { 'h', 'e', 'l', 'l', 'o' };
printf("%s\n", str1);
}
void copyString01(char *dst, const char *source)
{
int len = strlen(source);
for (int i = 0; i < len; ++i)
{
dst[i] = source[i];
}
dst[len] = '\0';
}
void copyString02(char *dst, const char *source)
{
while (*source != '\0')
{
*dst = *source;
++dst;
++source;
}
*dst = '\0';
}
void copyString03(char *dst, const char *source)
{
if (NULL == dst)
{
return;
}
if (NULL == source)
{
return;
}
while (*dst++ = *source++);
}
//1. 字符串拷贝
void test02()
{
char *source = "hello world!";
char buf[1024] = {0};
//copyString01(buf, source);
//copyString02(buf, source);
copyString03(buf, source);
printf("%s\n",buf);
}
void test04()
{
char *src = "hello world!";
char *temp = malloc(100);
char *p = temp;
while (*p++ = *src++);
printf("temp = %s\n", temp);
}
int main(){
test02();
system("pause");
return EXIT_SUCCESS;
}