如何根据某些字符分割字符串?经纬度

时间:2019-04-16 21:49:07

标签: c++

对于我的代码,用户输入位置的经度和纬度以及位置名称。例如,“ 33.9425 / N 118.4081 / W洛杉矶国际机场”。然后,程序使用经度和纬度计算一些信息。我是C ++的新手,但是我想到了使用python的字符串切片技术。但是,我不确定坐标将是多少位数,因此无法手动对其进行切片。在C ++中是否有一种方法只能将数字保留到特定字符?例如,仅获得33.9425和118.4081?

2 个答案:

答案 0 :(得分:0)

是的,您可以使用

string s {"abc"};
s.find("b");

评估符号的首次出现,然后使用substr()方法对字符串进行切片。

答案 1 :(得分:0)

这是经典的正则表达式问题。看看std::regex。我自己可以使用std::regex_iterator进行此操作。这应该起作用:

#include <map>
#include <string>
#include <tuple>
#include <utility>

namespace web
 {
   enum class attrs
    { charset, name, content, http_equiv, rel, href, id, src, lang };

   using attribute = std::pair<attrs, std::string>;

   using attribute_type = std::map<attrs, std::string>;

   const auto none = attribute_type{};

   enum tag_name
    { html, head, meta, title, link, body, div, script, plain, p, h1, span };

   template <typename... Tags>
   struct node
    {
      int increment;
      std::tuple<Tags...> tags;

      explicit node (int const incr, Tags ... tggs)
         : increment{incr}, tags{tggs...}
       { }
    };

   template <tag_name>
   struct w
    { };

   template <tag_name T, typename ... Tags>
   struct tag
    {
      attribute_type attributes;
      std::tuple<Tags...> tags;

      explicit tag (attribute_type atts)
         : attributes{std::move(atts)}
       { }

      explicit tag (w<T>, attribute_type atts, Tags... tggs)
         : attributes{std::move(atts)}, tags{tggs...}
      { }
    };

   template <>
   struct tag<plain>
    {
      std::string content;

      explicit tag (std::string val) : content{std::move(val)}
       { }
    };
 } // namespace web


int main ()
 {
   using namespace web;
   node page1{2};
   node page2{2, tag<html>{none}};
   node page3{2, tag<html>{{{attrs::lang, "en"}}}};
   node page4{2, tag<html>{{{attrs::name, "viewport"},
       {attrs::content, "width=device-width, initial-scale=1.0"}}}};
   node page5{2, tag<head>{none}, tag<body>{none},
       tag<plain>{"Hello World"}};
   node page6{1, tag{w<span>{}, none, tag<h1>{none}}};
 }

输出:

#include <regex>
#include <iterator>
#include <iostream>
#include <string>

int main()
{
    const std::string s = "33.9425/N 118.4081/W Los Angeles International Airport";

    std::regex words_regex("\\d+\\.\\d+");
    auto words_begin = 
        std::sregex_iterator(s.begin(), s.end(), words_regex);
    auto words_end = std::sregex_iterator();

    std::cout << "Found " 
              << std::distance(words_begin, words_end) 
              << " numbers:\n";

    for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
        std::smatch match = *i;                                                 
        std::string match_str = match.str(); 
        std::cout << match_str << '\n';
    }   
}

完全公开:我只是从cppreference.com的示例中Found 2 numbers: 33.9425 118.4081 中提取了上述内容,并对其进行了更改,而不是我自己的代码:)

相关问题