【问题标题】:C++ equivalent of Python String Slice?C++ 相当于 Python 字符串切片?
【发布时间】:2015-01-16 20:28:43
【问题描述】:

在 python 中,我能够对字符串的一部分进行切片;换句话说,只是在某个位置之后打印字符。在 C++ 中是否有与此等价的功能?

Python 代码:

text= "Apple Pear Orange"
print text[6:]

将打印:Pear Orange

【问题讨论】:

    标签: python c++ string


    【解决方案1】:

    是的,就是substr方法:

    basic_string substr( size_type pos = 0,
                         size_type count = npos ) const;
        
    

    返回一个子字符串 [pos, pos+count)。如果请求的子字符串超出了字符串的末尾,或者如果 count == npos,则返回的子字符串为 [pos, size())。

    示例

    #include <iostream>
    #include <string>
    
    int main(void) {
        std::string text("Apple Pear Orange");
        std::cout << text.substr(6) << std::endl;
        return 0;
    }
    

    See it run

    【讨论】:

      【解决方案2】:

      在 C++ 中,最接近的等价物可能是 string::substr()。 示例:

      std::string str = "Something";
      printf("%s", str.substr(4)); // -> "thing"
      printf("%s", str.substr(4,3)); // -> "thi"
      

      (第一个参数是初始位置,第二个是切片的长度)。 第二个参数默认为字符串结尾(string::npos)。

      【讨论】:

        【解决方案3】:
        std::string text = "Apple Pear Orange";
        std::cout << std::string(text.begin() + 6, text.end()) << std::endl;  // No range checking at all.
        std::cout << text.substr(6) << std::endl; // Throws an exception if string isn't long enough.
        

        请注意,与 python 不同,第一个不进行范围检查:您的输入字符串需要足够长。根据您对切片的最终用途,可能还有其他替代方案(例如直接使用迭代器范围,而不是像我在这里那样制作副本)。

        【讨论】:

          【解决方案4】:

          看起来 C++20 会有 Ranges https://en.cppreference.com/w/cpp/ranges 除其他外,它们旨在提供类似 python 的切片 http://ericniebler.com/2014/12/07/a-slice-of-python-in-c/ 所以我在等待它登陆我最喜欢的编译器,同时使用 https://ericniebler.github.io/range-v3/

          【讨论】:

            【解决方案5】:

            听起来你想要string::substr

            std::string text = "Apple Pear Orange";
            std::cout << text.substr(6, std::string::npos) << std::endl; // "Pear Orange"
            

            这里string::npos 是“直到字符串结尾”的同义词(也是默认值,但为了清楚起见,我将其包括在内)。

            【讨论】:

              【解决方案6】:

              你可以使用字符串类做这样的事情:

              std::string text = "Apple Pear Orange";
              size_t pos = text.find('Pear');
              

              【讨论】:

                【解决方案7】:

                **第一个参数确定起始索引,第二个参数指定结束索引记住字符串的开始是从0开始**

                string s="Apple";
                
                string ans=s.substr(2);//ple
                
                string ans1=s.substr(2,3)//pl
                

                【讨论】:

                  猜你喜欢
                  • 2014-07-21
                  • 2012-02-15
                  • 1970-01-01
                  • 2015-11-26
                  • 2013-10-29
                  • 2020-11-27
                  • 2019-04-27
                  • 1970-01-01
                  相关资源
                  最近更新 更多