【发布时间】:2020-08-20 12:19:39
【问题描述】:
我正在努力从 C 中的主字符串中删除混淆子字符串。子字符串的格式为xx:xx:xx:xx:xx:xx,其中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
有人可以告诉我可能出了什么问题吗?或者,如果您帮助更有效地执行此操作,请告诉我
【问题讨论】:
-
proc(*str)-->proc(str).