我正在努力从C语言的主字符串中删除一个子串的混淆,这个子串的格式是 xx:xx:xx:xx:xx:xx
哪儿 x
可以是一个数字或字母。子串的开头总是有一个空格,但子串的结尾并不总是有一个空格。
e.x. 输入可以是 "Found new device with wlan 33:33:33:33:33:33. Total 4 devices connected"
输出应该是 "Found new device with wlan *. Total 4 devices connected"
我需要做一个辅助函数来实现,这就是我想出的办法。
//find the first occurency of ":" record as first_position_ptr and the last occurency of ":" record as last_position_ptr.
// Add 2 to first_position_ptr to beginning of the substring and set it to "*"
// Subtract 2 from the last_position_ptr to get the pointer of the last charactor in substrung.
// Iterate from 1 + first_position_ptr to last_position_ptr - 2 and set inStr to 0 to deleted the rest of substring.
const char *proc(char *inStr) {
const char tar[] = ":";
char *first_position_ptr = strchr(inStr, tar[0]);
char *last_position_ptr = strrchr(inStr, tar[0]);
int first_position = (first_position_ptr == NULL ? -1 : first_position_ptr - inStr);
int last_position = (last_position_ptr == NULL ? -1 : last_position_ptr - inStr);
if (first_position != -1 && last_position != -1) {
inStr[first_position + 2] = "*";
}
for (int i = (first_position + 1); i < (last_position + 2); i++) {
inStr[i] = 0;
}
return inStr;
}
int main() {
const char str[] = "Found new device with wlan 33:33:33:33:33:33. Total 4 devices connected";
proc(*str);
printf("%s\n", str);
return 0;
}
但当我编译代码时,我遇到了这些警告。
Jeff-MacBook-Pro-2:Desktop jBerman$ gcc test.c -o test
test.c:35:29: warning: incompatible pointer to integer conversion assigning to 'char' from
'char [2]' [-Wint-conversion]
inStr[first_position + 2] = "*";
^ ~~~
test.c:43:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
test.c:49:7: warning: incompatible integer to pointer conversion passing 'const char' to
parameter of type 'char *' [-Wint-conversion]
proc(*str);
^~~~
test.c:26:24: note: passing argument to parameter 'inStr' here
const char* proc(char *inStr){
^
3 warnings generated.
当我运行它时,编译说:
Segmentation fault: 11
所以我试着在main中改正这行。
proc(*str) -> proc(&str);
编译器返回:
Bus error: 10
谁能告诉我可能出了什么问题?或者如果你有更有效的方法,请告诉我。
你应该通过 str
到 proc
,不 *str
并定义 str
作为一个可修改的 char
数组。proc
函数也应该简化:将中间的字符设置为零,并不会擦掉中间的部分,而是让字符串在后面的 *
. 要保留字符串的结尾,你必须用 memmove()
.
这里是一个修改版。
#include <stdio.h>
#include <string.h>
// replace the mac address from the input string with a *
char *proc(char *inStr) {
char *p1 = strchr(inStr, ':');
char *p2 = strrchr(inStr, ':');
if (p1) { // no need to test p2, there is at least one ':' in the string
/* backtrack 2 characters, but not before the start of inStr */
if (p1 > inStr) p1--;
if (p1 > inStr) p1--;
/* skip 3 characters, but not past the end of the string */
p2++;
if (*p2) p2++;
if (*p2) p2++;
/* replace the MAC address with a '*' */
*p1++ = '*';
/* move the rest of the string, including the null terminator */
memmove(p1, p2, strlen(p2) + 1);
}
return inStr;
}
int main() {
char str[] = "Found new device with wlan 33:33:33:33:33:33. Total 4 devices connected";
printf("%s\n", proc(str));
return 0;
}