给定一个字符串(作为函数的参数),在给定的字符组合之后,我需要删除零序列,如果退出(它只需要修改字符串)。例如,如果字符组合为x+
,则字符串20.301x+000005
必须转换为20.301x+5
。
我试过了:
void convertStr(char *analysisBuffer)
{
char *exp;
if( (exp = strstr(analysisBuffer,"x+"))!=NULL||(exp = strstr(analysisBuffer,"X+"))!= NULL)
{
exp += 2;
char * zeroIt = exp;
while(*zeroIt == '0')
++zeroIt;
unsigned int x = exp - analysisBuffer;
analysisBuffer[x] = '\0';
strcat(analysisBuffer,zeroIt);
}
}
有人可以告诉我如何正确实施吗?
答案 0 :(得分:3)
这是一个适用于表达式多次出现的版本 并减少字符串的大小,以便不占用内存 零终结者。这可能更慢,完全没必要 但是给你一种很棒的感觉。
免责声明:我很久没有写过任何纯粹的C.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strip_zero(char* str, const char* startseq) {
// while there is an occurence of the substring
size_t ssize = strlen(startseq);
size_t oldlen = strlen(str) + 1; // account for terminator
size_t rems = 0;
char* begin = str;
while((begin = strstr(begin, startseq))) {
// move to the end of the sequence
begin += ssize;
char* walk = begin;
// walk until we reach nonzero
while(*walk == '0') { ++walk; ++rems; }
// move the string forward
memmove(begin, walk, strlen(walk) + 1);
}
// realloc the string
return (char*)realloc(str, oldlen - rems);
}
int main(void)
{
// make a copy so we can modify
const char* a = "x+20.301x+00000x+0005x+";
char* foo = (char*)malloc(strlen(a) + 1);
strcpy(foo, a);
printf("%s \n", foo);
foo = strip_zero(foo, "x+");
printf("%s \n", foo);
free(foo);
return 0;
}
答案 1 :(得分:2)
以下是您想要的更完整的示例。我尝试改进一些项目:
strcasestr
函数进行不区分大小写的测试。 (我们需要#define _GNU_SOURCE
)strcat
(正如您所做的那样)将字符串的尾部附加到头部。char test[] = "..."
而不是char *test = "..."
,因为后者会出现段错误。 while
之类的函数摆脱rindex()
循环,它会为字符串中的字符提供最正确的索引。#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void
convertStr(char *analysisBuffer)
{
char *exp = strcasestr(analysisBuffer, "x+");
if (exp) {
exp += 2;
if (*exp == '0') {
while (*exp == '0') {
*exp = '\0';
exp++;
}
strcat(analysisBuffer, exp);
}
}
}
int
main(int argc, char *argv[])
{
char test[] = "20.301X+0005";
printf("before: %s\n", test);
convertStr(test);
printf("after : %s\n", test);
return EXIT_SUCCESS;
}
答案 2 :(得分:1)
像
这样的东西char * write = str;
char * read = str;
while(*read){
while(*read && *read == '0'){ read++; }
*write++ = *read++;
}
*write = '\0';
? (这是未经测试的)
答案 3 :(得分:1)
而不是:
unsigned int x = exp - analysisBuffer;
analysisBuffer[x] = '\0';
strcat(analysisBuffer,zeroIt);
你可以这样做:
memmove(exp, zeroIt, strlen(zeroIt) + 1);
答案 4 :(得分:1)
size_t strip0( char *buff);
size_t strip0( char *buff)
{
size_t src,dst;
for (src=dst=0; buff[dst] = buff[src++] ;dst++ ) {
if ((buff[dst] == 'x' || buff[dst] == 'X') && buff[src] == '+') {
buff[++dst] = buff[src++] ;
while (buff[src] == '0') src++;
}
}
return dst;
}
#include <stdio.h>
int main(int arc, char **argv)
{
char data[] = "100x+003 aap 200x+300 100X+003 noot 200X+300 mies 1234xX+000000000zzz";
printf("Org: %s\n", data);
strip0(data);
printf("New: %s\n", data);
return 0;
}