C语言 C:获取某个字符前的子串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15006269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C: Get substring before a certain char
提问by Itzik984
For example, I have this string: 10.10.10.10/16
例如,我有这个字符串: 10.10.10.10/16
and I want to remove the mask from that IP and get: 10.10.10.10
我想从该 IP 中删除掩码并获得: 10.10.10.10
How could this be done?
这怎么可能?
采纳答案by pmg
Just put a 0 at the place of the slash
只需在斜线处放一个 0
#include <string.h> /* for strchr() */
char address[] = "10.10.10.10/10";
char *p = strchr(address, '/');
if (!p)
{
/* deal with error: / not present" */
;
}
else
{
*p = 0;
}
I don't know if this works in C++
我不知道这是否适用于 C++
回答by Andy Prowl
Here is how you would do it in C++ (the question was tagged as C++ when I answered):
以下是您在 C++ 中的做法(当我回答时,问题被标记为 C++):
#include <string>
#include <iostream>
std::string process(std::string const& s)
{
std::string::size_type pos = s.find('/');
if (pos != std::string::npos)
{
return s.substr(0, pos);
}
else
{
return s;
}
}
int main(){
std::string s = process("10.10.10.10/16");
std::cout << s;
}
回答by 75inchpianist
char* pos = strstr(IP,"/"); //IP: the original string
char [16]newIP;
memcpy(newIP,IP,pos-IP); //not guarenteed to be safe, check value of pos first
回答by Roee Gavirel
I see this is in C so I guess your "string" is "char*"?
If so you can have a small function which alternate a string and "cut" it at a specific char:
我看到这是在 C 中,所以我猜你的“字符串”是“char *”?
如果是这样,您可以使用一个小函数来交替字符串并在特定字符处“剪切”它:
void cutAtChar(char* str, char c)
{
//valid parameter
if (!str) return;
//find the char you want or the end of the string.
while (*char != '#include <iostream>
using namespace std;
int main()
{
std::string addrWithMask("10.0.1.11/10");
std::size_t pos = addrWithMask.find("/");
std::string addr = addrWithMask.substr(0,pos);
std::cout << addr << std::endl;
return 0;
}
' && *char != c) char++;
//make that location the end of the string (if it wasn't already).
*char = 'char ipmask[] = "10.10.10.10/16";
char ip[sizeof(ipmask)];
char *slash;
strcpy(ip, ipmask);
slash = strchr(ip, '/');
if (slash != 0)
*slash = 0;
';
}
回答by Thiago Navarro
Example in C++
C++ 中的示例
##代码##
