【问题标题】:C: Get substring before a certain charC:获取某个字符之前的子字符串
【发布时间】:2013-02-07 00:19:40
【问题描述】:

例如,我有这个字符串:10.10.10.10/16

我想从该 IP 中删除掩码并获取:10.10.10.10

这是怎么做到的?

【问题讨论】:

  • 你可以结合std::string::substr()std::string::find()
  • 如果你可以销毁原始字符串,你可以使用strchr('/') = '\0'
  • 你也可以使用memchr函数,然后strcpy
  • std::string 还是 char*?
  • C 或 C++。一种语言的答案不一定对另一种语言有效。

标签: c string char


【解决方案1】:

这是你在 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;
}

【讨论】:

  • 真的很抱歉,c是我需要的
【解决方案2】:

在斜线的位置放一个 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;
}

我不知道这是否适用于 C++

【讨论】:

  • 浪费内存!全部 3 个字节!
  • @75inchpianist 你这是什么意思?内存在哪里“浪费”了?
  • 不应该是*p = '\0';
  • @Shutupsquare:除了源代码形式外,'\0'0 完全一样。第一个是文字字符:它的类型为int,值0;第二个是文字整数:它的类型为int,值0C++ 中的情况可能有所不同。我不懂那种语言。
【解决方案3】:
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

【讨论】:

    【解决方案4】:

    我看到这是在 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 != '\0' && *char != c) char++;
    
        //make that location the end of the string (if it wasn't already).
        *char = '\0';
    }
    

    【讨论】:

      【解决方案5】:

      C++ 示例

      #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;
       }
      

      【讨论】:

        【解决方案6】:

        中的示例

        char ipmask[] = "10.10.10.10/16";
        char ip[sizeof(ipmask)];
        char *slash;
        strcpy(ip, ipmask);
        slash = strchr(ip, '/');
        if (slash != 0)
            *slash = 0;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-14
          • 1970-01-01
          • 1970-01-01
          • 2018-08-21
          • 2014-11-24
          • 2010-12-23
          • 2021-01-09
          • 1970-01-01
          相关资源
          最近更新 更多