C语言实现string结构体

string.h

#ifndef STRING_H
#define STRING_H

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

typedef struct
{
	char * s;
	int len;
} string;

string string_construct(const char * str)
{
	string s;
	s.len = strlen(str);
	s.s = (char *) malloc(s.len + 1);
	strcpy(s.s, str);
	return s;
}

string string_copyconstruct(string ss)
{
	string s;
	s.s = (char *) malloc(ss.len + 1);
	strcpy(s.s, ss.s);
	s.len = ss.len;
	return s;
}

void string_print(string s, FILE * stream)
{
	fprintf(stream, "%s", s.s);
}

void string_change(string * s, const char * str)
{
	free(s -> s);
	*s = string_construct(str);
}

int string_compare(string s1, string s2)
{
	return strcmp(s1.s, s2.s);
}

string string_concate(string s1, string s2)
{
	string s;
	s.len = strlen(s1.s) + strlen(s2.s) + 1;
	s.s = (char *) malloc(s.len);
	strcpy(s.s, s1.s);
	strcat(s.s, s2.s);
	return s;
}

#endif

try_string_h.c

#include<stdio.h>
#include"string.h"
int main(void)
{
	printf("Part 1: Try constructor and print function\n");
	string s = string_construct("EricPythonBlogs");
	printf("Display the string: ");
	string_print(s, stdout);
	printf("\nPart 2: Try copy constructor and assignment function\n");
	string s1 = string_copyconstruct(s);
	printf("Display the string after copy-constructed: ");
	string_print(s1, stdout);
	string_change(&s1, "I am a C student. ");
	printf("\nDisplay the string after assigned: ");
	string_print(s1, stdout);
	printf("\nPart 3: Try comparing and concatenation function\n");
	printf("Compare result is: %d\n", string_compare(s, s1));
	string_change(&s, string_concate(s, s1).s);
	printf("Concate result is: ");
	string_print(s, stdout);
	return 0;
}

运行结果:

Part 1: Try constructor and print function
Display the string: EricPythonBlogs
Part 2: Try copy constructor and assignment function
Display the string after copy-constructed: EricPythonBlogs
Display the string after assigned: I am a C student.
Part 3: Try comparing and concatenation function
Compare result is: -1
Concate result is: EricPythonBlogsI am a C student.

嗯,如果要写将一个字符串连接上另一个C字符串,就要这样写:

string_change(&s1, string_concate(s1, string_construct("second string")).s);

这挺复杂的,但还能用用。

大家可以改进哦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值