变量可以包含3-4HYTER3(OK)或[ID] =" 3-4HYTER3" (错误的)
需要在字符串中剪切错误符号,如:[ID] =" 3-4HYTER3" 应该是:3-4HYTER3
如何找到错误的字符串[ID] = 3-4HYTER3并剪切[ID] =" " ?
拜托,帮助我!
答案 0 :(得分:0)
如果我了解你,你需要像 -
这样的东西const char *removeId(const char *input) {
const char *pattern = "[ID] = \"";
const size_t patternLen = strlen(pattern);
if (strncmp(input, pattern, patternLen) == 0) {
size_t outLen = strlen(input) - patternLen;
char *out = (char *) malloc(sizeof(char *) * outLen);
strncpy(out, input+patternLen, outLen - 1);
out[outLen - 1] = '\0';
return out;
}
return input;
}
int main(int argc, char *argv[]) {
const char *input = "[ID] = \"3-4HYTER3\"";
puts(input);
puts(removeId(input));
}
输出
[ID] = "3-4HYTER3"
3-4HYTER3
答案 1 :(得分:0)
除了关于删除不需要的ID的答案之外,如果要搜索大量字符串以识别包含不需要的字符的字符串,例如示例中的=
符号,则可以使用简单的函数来搜索字符串中的字符并根据需要采取措施:
/* char in string - returns 1 if found, 0 otherwise
(could make (void *) and return 'p' or NULL)
*/
int
chr_in_str (char *str, char c)
{
char *p = str;
while (*p != '\0') {
if (*p == c)
return 1;
p++;
}
return 0;
}
只需在测试中传递字符串和感兴趣的字符:
if (chr_in_str (str, '='))
removeId (str); // removeId from Elliots answer
答案 2 :(得分:0)
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define VALID_CHAR_SET "abcdefghijklmnopqrstuvwxyz"\
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"\
"0123456789"\
"-_"
static inline bool isValidChar(char ch){
//or use is isalnum() etc.. in <ctype.h>
// return isalnum(ch) || ch == '-' /* ... */;
return !!strchr(VALID_CHAR_SET, ch);//Simple implementation
}
int removeInvalidChar(char *str){
char *to;
int count = 0;
for(to=str;*str;++str){
if(isValidChar(*str))
*to++ = *str;
else
++count;
}
*to = '\0';
return count;
}
int main(){
char str[]="\"3-4HYTER3\"";
if(removeInvalidChar(str)){
printf("removed the invalid character.\n");
}
printf("%s\n", str);
return 0;
}