topic
Statistics need to insert the number of characters in the string. Such as string aaabc, the number of characters inserted into aaa3b1c1
Code
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;
}
Code compilation
gcc main.c str.c -g -o a.exe
Debug output
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