3.1 C/C++ 使用字符与指针

C/C++语言是一种通用的编程语言,具有高效、灵活和可移植等特点。C语言主要用于系统编程,如操作系统、编译器、数据库等;C语言是C语言的扩展,增加了面向对象编程的特性,适用于大型软件系统、图形用户界面、嵌入式系统等。C/C++语言具有很高的效率和控制能力,但也需要开发人员自行管理内存等底层资源,对于初学者来说可能会有一定的难度。

strtok 字符串切割: 将指定的一段字符串,根据指定的分隔符进行切割,切割后分别存入到新数组.

#include <stdio.h>

int main(int argc, char* argv[])
{
char str[] = "hello,lyshark,welcome";
char *ptr;

ptr = strtok(str, ",");
while (ptr != NULL)
{
printf("切割元素: %s\n", ptr);
ptr = strtok(NULL, ",");
}

char str[] = "192.168.1.1";
char *ptr;
char *SubAddr[4] = {0};

ptr = strtok(str, ".");
for (int x = 0; x < 4; x++)
{
SubAddr[x] = ptr;
ptr = strtok(NULL, ".");
}

for (int x = 0; x < 4; x++)
printf("%s \n", SubAddr[x]);

system("pause");
return 0;
}

strcpy 字符串拷贝: 将一个字符串数组中的数据拷贝到新的字符串空间中,拷贝知道遇到结束符为止.

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
char Array[] = "hello lyshark";
char tmp[100];

// 学习strcpy函数的使用方式
if (strcpy(tmp, Array) == NULL)
printf("从Array拷贝到tmp失败\n");
else
printf("拷贝后打印: %s\n", tmp);

// 清空tmp数组的两种方式
for (unsigned int x = 0; x < strlen(tmp); x++)
tmp[x] = ' ';

memset(tmp, 0, sizeof(tmp));

// 学习strncpy函数的使用方式
if (strncpy(tmp, Array, 3) == NULL)
printf("从Array拷贝3个字符到tmp失败\n");
else
printf("拷贝后打印: %s\n", tmp);

system("pause");
return 0;
}

strcat 字符串连接: 将由src指向的字节串的副本,追加到由dest指向的以空字节终止的字节串的末尾.

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
char str1[50] = "hello ";
char str2[50] = "lyshark!";

char * str = strcat(str1, str2);
printf("字符串连接: %s \n", str);

str = strcat(str1, " world");
printf("字符串连接: %s \n", str);

str = strncat(str1, str2, 3);
printf("字符串连接: %s \n", str);

system("pause");
return 0;
}

strcmp 字符串对比: 对比两个字符串是否一致,如果一致返回真否则返回假,此外如需要对比指定长度,可用strncmp()函数.

#include <stdio.h>
#include <string.h>

int Str_Cmp(const char * lhs, const char * rhs)
{
int ret = strcmp(lhs, rhs);
if (ret == 0)
return 1;
else
return 0;
}

int main(int argc, char* argv[])
{
char *str1 = "hello lyshark";
char *str2 = "hello lyshark";

int ret = Str_Cmp(str1, str2);
printf("字符串是否相等: %d \n", ret);

if (!strncmp(str1, str2, 3))
printf("两个字符串,前三位相等");

system("pause");
return 0;
}

strshr 字符串截取: 该函数主要实现从指定位置开始向后截取,直到遇到结束符停止输出.

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
const char buffer[32] = "hello lyshark welcome";
const char needle[10] = "lyshark";
const char* ret;

ret = strstr(buffer, needle);
printf("子字符串是: %s \n", ret);

system("pause");
return 0;
}

sprintf 格式化字符串: 该函数主要实现了对一段特定字符串进行格式化后并写入到新的缓冲区内.

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
// 格式化填充输出
char buf[30] = { 0 };
sprintf(buf, "hello %s %s", "lyshark","you are good");
printf("格式化后: %s \n", buf);

// 拼接字符串
char *s1 = "hello";
char *s2 = "lyshark";
memset(buf, 0, 30);
sprintf(buf, "%s --> %s", s1, s2);
printf("格式化后: %s \n", buf);

// 数字装换位字符串
int number = 100;
memset(buf, 0, 30);
sprintf(buf, "%d", number);
printf("格式化后: %s \n", buf);

system("pause");
return 0;
}

动态存储字符串: 首先分配二维指针并开辟空间,每次循环时开辟一维空间,并向其中写入字符串,最后循环输出.

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
// 分配空间
char **p = malloc(sizeof(char *)* 5);

for (int x = 0; x < 5;++x)
{
p[x] = malloc(64);
memset(p[x], 0, 64);
sprintf(p[x], "Name %d", x + 1);
}

// 打印字符串
for (int x = 0; x < 5; x++)
printf("%s \n", p[x]);

// 释放空间
for (int x = 0; x < 5; x++)
{
if (p[x] != NULL)
free(p[x]);
}

system("pause");
return 0;
}

实现字串长度统计: 字符串长度的计算原理时循环判断字符串是否遇到了\0并每次递增,遇到后直接返回.

#include <stdio.h>
#include <string.h>

// 自己实现的一个字符串统计函数
int MyStrlen(char * String)
{
int length = 0;
// 写法一
while (*String++ != '\0')
length++;
// 写法二
//while (String[length] != '\0')
// length++;

return length;
}

int main(int argc, char* argv[])
{
char *StringA = "hello lyshark";
char *StringB = "lyshark";
char StringC[] = { 'l', 'y', 's', 'h', 'a', 'r', 'k','\0'};

int string_len = strlen(StringA);
printf("字符串长度: %d \n", string_len);

int string_cmp = strlen(StringA) > strlen(StringB);
printf("字符串大小比较: %d \n", string_cmp);

int my_string_len = MyStrlen(StringC);
printf("字符串长度: %d \n", my_string_len);

system("pause");
return 0;
}

实现字符串拷贝: 字符串拷贝函数其原理是将源地址中的数据依次复制到目标中.

#include <stdio.h>
#include <string.h>

// 使用数组实现字符串拷贝
void CopyString(char *dest,const char *source)
{
int len = strlen(source);
for (int x = 0; x < len; x++)
{
dest[x] = source[x];
}
dest[len] = '\0';
}

// 使用指针的方式实现拷贝
void CopyStringPtr(char *dest, const char *source)
{
while (*source != '\0')
{
*dest = *source;
++dest, ++source;
}
*dest = '\0';
}
// 简易版字符串拷贝
void CopyStringPtrBase(char *dest, const char *source)
{
while (*dest++ = *source++);
}

int main(int argc, char* argv[])
{
char * str = "hello lyshark";
char buf[1024] = { 0 };
CopyStringPtrBase(buf, str);
printf("%s \n", buf);

system("pause");
return 0;
}

实现查找字符串: 查找字符串函数MyStrStr()实现了在指定字符串中寻找字串,找到后返回之后的数据.

#include <stdio.h>
#include <string.h>

char * MyStrStr(char * dest, char *src)
{
char * p = NULL;
char * temp = src;
while (*dest)
{
p = dest;
while (*dest == *temp && *dest)
{ dest++; temp++; }
if (!*temp)
return p;
else
temp = src;
dest = p; dest++;
}
return NULL;
}

int main(int argc, char* argv[])
{
char *p = MyStrStr("hello lyshark", "shark");
printf("找到子串: %s\n", p);

system("pause");
return 0;
}

实现字符串拼接: 自己实现字符串追加拼接,把String所指向的字符串追加到dest所指向的字符串的结尾.

#include <stdio.h>
#include <string.h>

void MyStrCat(char * String, char * SubStr)
{ // 将指针移动到末尾
while (*String != NULL)
String++;
// 开始拷贝
while (*SubStr != NULL)
{
*String = *SubStr;
String++; SubStr++;
}
*String = '\0';
}

int main(int argc, char* argv[])
{
char String[100] = "hello";
char * Sub = " lyshark";

MyStrCat(String, Sub);
printf("拼接字符串: %s\n", String);

system("pause");
return 0;
}

实现字符串去空格: 实现对字符串中空格的去除,循环判断原字符串是否有空格,如果有则跳过,没有则追加.

#include <stdio.h>
#include <string.h>

char * RemoveSpace(char * String)
{
char * start = String;
char * end = String + strlen(String) - 1;
while (*end == ' ' && end > start)
end--;
*(end + 1) = '\0';

while (*start == ' ' && start < end)
start++;
return start;
}

int main(int argc, char* argv[])
{
char str[] = " hello lyshark ";

char *ptr = RemoveSpace(str);
printf("原字符串: %s 新字符串: %s \n", str,ptr);

system("pause");
return 0;
}

实现字符串逆序: 实现将指定的字符串逆序,其原理是将字符串首尾互换位置,循环更改原字符串.

#include <stdio.h>
#include <string.h>

void Strswap(char *Array)
{
int len = strlen(Array);
char *p1 = Array;
char *p2 = &Array[len - 1];
while (p1 < p2)
{
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
p1++, p2--;
}
}

int main(int argc, char* argv[])
{
char str[20] = "hello lyshark";
Strswap(str);

for (int x = 0; x < strlen(str); x++)
printf("%c", str[x]);

system("pause");
return 0;
}

实现字符串截取: 实现在参数String所指向的字符串中搜索第一次出现字符ch的位置,并输出其后内容.

#include <stdio.h>
#include <string.h>

char * MyStrchr(const char *String, char ch)
{
char *ptr = String;
while (*ptr != '\0')
{
if (*ptr == ch)
return ptr;
ptr++;
}
return NULL;
}

int main(int argc, char* argv[])
{
char Str[] = "hello lyshark";
char ch = 's';

char *ptr = MyStrchr(Str, ch);
printf("输出结果: %s \n", ptr);

system("pause");
return 0;
}

字符串首字母排序: 实现传入一个指针数组,函数将根据字符串第一个字母进行排序,排序影响原数组.

#include <stdio.h>
#include <string.h>

void bubble(char **Str, int len)
{
for (int x = 0; x < len - 1; x++)
{
for (int y = 0; y < len - x - 1; y++)
{
if (**(Str + y) < **(Str + y + 1))
{
char * tmp = *(Str + y);
*(Str + y) = *(Str + y + 1);
*(Str + y + 1) = tmp;
}
}
}
}

int main(int argc, char* argv[])
{
char *Str[] = { "csdfw", "qwesfae", "retyu", "wsf" };


int len = sizeof(Str) / sizeof(char *);
bubble(Str,len);

for (int x = 0; x < len; x++)
printf("%s \n", Str[x]);

system("pause");
return 0;
}

实现字符串的匹配: 该函数与strchr()类似,不过当StringMatch()函数匹配成功后会返回一个位置而不是字符串.

#include <stdio.h>
#include <string.h>

int StringMatch(char *String, char *SubString)
{
int x, y, start = 0;
int str_len = strlen(String) - 1; // 得到主字符串长度
int sub_len = strlen(SubString) - 1; // 得到子字符串长度
int end_match = sub_len;

for (y = 0; end_match <= str_len; end_match++, start++)
{
if (String[end_match] == SubString[sub_len])
{
for (y = 0, x = start; y < sub_len && String[x] == SubString[y];)
x++, y++;
}

if (y == sub_len)
return (start + 1);
}
if (end_match > String)
return -1;
}

int main(int argc, char* argv[])
{
char str[] = "hello lyshark welcome !";
char sub[] = "lyshark";

int ret = StringMatch(str, sub);
if (ret != -1)
{
printf("匹配到,字符间隔: %d \n", ret);
}

system("pause");
return 0;
}

统计字符串字符个数: 实现循环一段字符串,每次取出一个字符并判断该字符是字母数组还是空格.

#include <stdio.h>
#include <string.h>

void String_Count(char *String)
{
int letter = 0, digit = 0, space = 0, other = 0;
int len = strlen(String);

for (int x = 0; x < len; x++)
{
char ch = (char)String[x];
if (ch != EOF)
{
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z')
letter++;
else if (ch >= '0' && ch <= '9')
digit++;
else if (ch == ' ')
space++;
else
other++;
}
}
printf("字符: %d -> 数字: %d -> 空格: %d -> 其他: %d \n", letter, digit, space, other);
}

int main(int argc, char* argv[])
{
char *str = "hello lyshark !@#$ 123456";
String_Count(str);

char *str1 = "please input &*(123";
String_Count(str1);

system("pause");
return 0;
}

指针实现字符串排序: 实现通过指针判断字符串位置,排序将按照A-Z的顺序进行.

#include <stdio.h>
#include <string.h>

void String_Sort(char *String[],int len)
{
char *temporary;
int x, y;

for (x = 0; x < len; x++)
{
for (y = x + 1; y < len; y++)
{
if (strcmp(String[x], String[y]) > 0)
{
temporary = String[x];
String[x] = String[y];
String[y] = temporary;
}
}
}
}

int main(int argc, char* argv[])
{
char *str[] = { "CPP", "Basic", "LyShark", "Hello", "Great" };
char **ptr = str;

String_Sort(str, 5);

for (int x = 0; x < 5; x++)
printf("%s \n", str[x]);

system("pause");
return 0;
}

实现字符串替换: 实现将string缓冲区里面的字符串{}符号,替换为%d字符.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>

int ReplaceStr(char* sSrc, char* sMatchStr, char* sReplaceStr)
{
int StringLen;
char caNewString[64];
char* FindPos;
FindPos = (char *)strstr(sSrc, sMatchStr);
if ((!FindPos) || (!sMatchStr))
return -1;

while (FindPos)
{
memset(caNewString, 0, sizeof(caNewString));
StringLen = FindPos - sSrc;
strncpy(caNewString, sSrc, StringLen);
strcat(caNewString, sReplaceStr);
strcat(caNewString, FindPos + strlen(sMatchStr));
strcpy(sSrc, caNewString);
FindPos = (char *)strstr(sSrc, sMatchStr);
}
free(FindPos);
return 0;
}

int main(int argc, char **argv)
{
char string[] = "192.168.1.{}";

BOOL ret = ReplaceStr(string, "{}", "%d");
if (ret == 0)
printf("%s \n", string);

system("pause");
return 0;
}