C language practical algorithm series strtok string segmentation, strcat string splicing, strcpy, strcmp

Code

#define _CRT_SECURE_NO_WARNINGS

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

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[] = " ,\t\n";
char *token;

int main(void)
{
    
    
	printf("Tokens:\n");

	// Establish string and get the first token:
	token = strtok(string, seps); // C4996
								  // Note: strtok is deprecated; consider using strtok_s instead
	while (token != NULL)
	{
    
    
		// While there are tokens in "string"
		printf(" %s\n", token);

		// Get next token: 
		token = strtok(NULL, seps); // C4996
	}
}

/*
	int i = -1;
	do
	{
		pDest[++i] = pSource[i];
	} while (pSource[i]);
*/
void StringCopy(char* pDest, char* pSource) //微软源码
{
    
    
	int i = -1;
	while (pDest[++i] = pSource[i])
		;
}

void StrCopy(char* pDest, char* pSrc)
{
    
    
	while(*pDest=*pSrc)
	{
    
    
		++pDest;
		++pSrc;
	}
}

void StrCat(char* pDest,char* pSrc)
{
    
    
	int i=0,j=0;
	while(pDest[i]!=0)
		++i;
	while(pDest[i++]=pSrc[j++])
		;
}

void StrCat1(char* pDest, char* pSrc)
{
    
    
	while (*pDest)
		++pDest;
	while (*pDest = *pSrc)
		++pDest, ++pSrc;
}

int StrCmp(char* s1, char* s2)
{
    
    
	unsigned char* p1 = (unsigned char*)s1;
	unsigned char* p2 = (unsigned char*)s2;
	while (*p1 && *p1++ == *p2++)
		;
	return *p1 - *p2;
}
  • %p %x %X difference, %p is better
  • Pointer subtraction, p1-p2 = address difference/sizeof(type)

operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/wlwdecs_dn/article/details/111064026