字符串中的连续字符统,并将统计数字插入到原有字符串中 -- C语言

题目

需要在字符串中插入字符统计的个数。 例如字符串 aaabc, 插入字符个数后变成 aaa3b1c1

 

代码实现

int statStr(char * str){
	if(NULL == str){
		printf("statStr param error\n");
		return PARAM_ERR;
	}

	int len = strlen(str) + 1; /*加上 '\0'*/
	int scanlen = 0; /*扫描的长度,从1开始*/
	int stat = 1;
	char * p = NULL;
	char * q = NULL;
	char s;

	p = str;
	while('\0' != *p){
		q = p;
		stat = 0; /*至少有自己重复*/
		while('\0' != q && *q == *p){
			stat++;
			q++;
		}
		scanlen += stat;

		s = stat + '0';
		memcpy(p + stat + 1, p + stat, len - scanlen);	
		*(p + stat) = s; /*填入统计数字*/
		scanlen += 1; 	/*因为插入了一个数字*/
		len = len + 1; 	/*因为插入了一个数字*/
		p = p + stat + 1; /* + 1 因为插入了一个数字*/
	}

	return SUCCESS;	
	
}


void teststatStr(void){
	char str[100] = "aaabc";

	printf("\n************  teststatStr ************ \n");

	statStr(str);

	printf("Stat str is: %s\n", str);

	return;	
}

代码编译

gcc main.c str.c -g -o a.exe

调试输出

GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/renmian/interview/a.exe...done.
(gdb) b str.c:498
Breakpoint 1 at 0x4015b3: file str.c, line 498.
(gdb) r
Starting program: /home/renmian/interview/./a.exe


************  teststatStr ************

Breakpoint 1, statStr (str=0x7fffffffe450 "aaabc") at str.c:498
498                     q = p;
(gdb) p str
$1 = 0x7fffffffe450 "aaabc"
(gdb) n
499                     stat = 0; /*至少有自己重复*/
(gdb) c
Continuing.

Breakpoint 1, statStr (str=0x7fffffffe450 "aaa3bc") at str.c:498
498                     q = p;
(gdb) p str
$2 = 0x7fffffffe450 "aaa3bc"
(gdb) n
499                     stat = 0; /*至少有自己重复*/
(gdb) c
Continuing.

Breakpoint 1, statStr (str=0x7fffffffe450 "aaa3b1c") at str.c:498
498                     q = p;
(gdb) p str
$3 = 0x7fffffffe450 "aaa3b1c"
(gdb) c
Continuing.
Stat str is: aaa3b1c1
[Inferior 1 (process 14942) exited normally]
(gdb) p str
No symbol "str" in current context.
(gdb) q

 

字符串中的连续字符统,并将统计数字插入到原有字符串中  -- C语言字符串中的连续字符统,并将统计数字插入到原有字符串中  -- C语言 leoufung 发布了212 篇原创文章 · 获赞 44 · 访问量 26万+ 私信 关注
上一篇:nvdla epython用于自动生成状态机编码的实例


下一篇:stat命令的实现-mysate 2075310