bool parseSession(char* buf, struct parseParameter* mPara) { char session[32] = { 0 }; std::string rBuf = buf; std::size_t pos = rBuf.find("Session"); if (pos != std::string::npos) { sscanf(rBuf.c_str() + pos, "%*[^:]: %s", session); strcpy(mPara->session, session); return true; } else { return false; } }C语言怎么实现相同的效果
时间: 2024-04-15 14:31:40 浏览: 8
要在 C 语言中实现与上述代码相同的效果,您可以使用 C 字符串库和字符串处理函数来完成。下面是一个类似的实现:
```c
#include <stdio.h>
#include <string.h>
typedef struct {
char session[32];
} parseParameter;
int parseSession(char* buf, parseParameter* mPara) {
char session[32] = {0};
char* pos = strstr(buf, "Session");
if (pos != NULL) {
sscanf(pos, "%*[^:]: %s", session);
strcpy(mPara->session, session);
return 1;
} else {
return 0;
}
}
```
在这个示例中,我们使用了 `sscanf` 函数来解析字符串,并使用 `strcpy` 函数将结果复制到 `mPara->session` 中。`strstr` 函数用于查找子字符串的位置。
请注意,C 语言中没有内置的字符串类型,所以我们使用字符数组来存储字符串。此外,要确保字符数组足够大以容纳字符串,并在最后一个字符后添加空字符。
希望这个示例能帮助您理解如何在 C 语言中实现相同的效果。如果还有其他问题,请随时提问。
相关问题
bool parseVideoPort(char* buf, struct parseParameter* mPara) { uint16_t RtpVideoPort = 0; uint16_t RtcpVideoPort = 0; std::string rBuf = buf; std::size_t pos = rBuf.find("Transport"); if (pos != NULL) { if ((pos = rBuf.find("RTP/AVP")) != std::string::npos) { pos = rBuf.find("server_port", pos); if (pos != std::string::npos) { sscanf(rBuf.c_str() + pos, "%*[^=]=%hu-%hu", &RtpVideoPort, &RtcpVideoPort); mPara->mRtpVideoPort = RtpVideoPort; mPara->mRtcpVideoPort = RtcpVideoPort; return true; } } } else { return false; } }C语言怎么实现相同的效果
要在 C 语言中实现与上述代码相同的效果,您可以使用 C 字符串库和字符串处理函数来完成。下面是一个类似的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
uint16_t mRtpVideoPort;
uint16_t mRtcpVideoPort;
} parseParameter;
int parseVideoPort(char* buf, parseParameter* mPara) {
uint16_t RtpVideoPort = 0;
uint16_t RtcpVideoPort = 0;
char* pos = strstr(buf, "Transport");
if (pos != NULL) {
if ((pos = strstr(pos, "RTP/AVP")) != NULL) {
pos = strstr(pos, "server_port");
if (pos != NULL) {
sscanf(pos, "%*[^=]=%hu-%hu",
&RtpVideoPort, &RtcpVideoPort);
mPara->mRtpVideoPort = RtpVideoPort;
mPara->mRtcpVideoPort = RtcpVideoPort;
return 1;
}
}
}
return 0;
}
```
在这个示例中,我们使用了 `sscanf` 函数来解析字符串,并将结果存储在相应的变量中。`strstr` 函数用于查找子字符串的位置。
请注意,在 C 语言中,我们需要使用指针来操作字符串,并使用相应的指针运算来处理字符串的位置。
希望这个示例能帮助您理解如何在 C 语言中实现相同的效果。如果还有其他问题,请随时提问。
std::map const char* 作为key
在 C++ 中,可以使用 `std::map` 容器来存储一组键值对,其中键和值可以是各种类型。如果想将 `const char*` 作为键,可以使用 `std::string` 或者自定义比较函数作为键的类型。
例如,可以定义一个比较函数 `cmp`,用来比较两个 `const char*` 类型的字符串:
```c++
struct cmp {
bool operator()(const char* a, const char* b) const {
return std::strcmp(a, b) < 0;
}
};
```
然后,可以使用 `std::map<const char*, int, cmp>` 来定义一个键为 `const char*` 类型,值为 `int` 类型的 `map` 容器,其中第三个参数为自定义的比较函数 `cmp`。这样就可以使用字符串作为键来进行映射了。例如:
```c++
std::map<const char*, int, cmp> m;
m["apple"] = 1;
m["banana"] = 2;
m["orange"] = 3;
std::cout << m["apple"] << std::endl; // 输出 1
```
需要注意的是,使用 `const char*` 作为键时,需要自己管理字符串的内存,避免出现悬空指针或者内存泄漏等问题。可以考虑使用 `std::string` 来代替 `const char*`,从而避免这些问题。