拆分字符串的程序不起作用?

Program that splits strings isn't working?

本文关键字:不起作用 程序 字符串 拆分      更新时间:2023-10-16

我创建了一个程序,该程序基于.将字符串拆分为更多的字符串例如,假设我输入字符串

Workspace.SiteNet.Character.Humanoid

应该打印

Workspace
SiteNet
Character
Humanoid

但是,它打印

Workspace
SiteNet.Character
Character.Humanoid
Humanoid

这就是代码。

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <WinInet.h>
#include <fstream>
#include <istream>
#include <iterator>
#include <algorithm>
#include <string>
#include <Psapi.h>
#include <tlhelp32.h>

int main() {
  std::string str;
  std::cin >> str;
  std::size_t pos = 0, tmp;
  std::vector<std::string> values;
  while ((tmp = str.find('.', pos)) != std::string::npos) {
    values.push_back(str.substr(pos, tmp));
    pos = tmp + 1;
  }
  values.push_back(str.substr(pos, tmp));
  for (pos = 0; pos < values.size(); ++pos){
    std::cout << "String part " << pos << " is " << values[pos] << std::endl;
  }
  Sleep(5000);
}

您的问题是传递给str.substr 的参数

string::substr采用两个参数:起始位置和要提取的子字符串的长度。

std::vector<std::string> split_string(const string& str){
    std::vector<std::string> values;
    size_t pos(0), tmp;
    while ((tmp = str.find('.',pos)) != std::string::npos){
        values.push_back(str.substr(pos,tmp-pos));
        pos = tmp+1;
    }
    if (pos < str.length())  // avoid adding "" to values if '.' is last character in str
        values.push_back(str.substr(pos));
    return values;
}

我认为更容易找到s中的最后一个点,将点后面所有东西的子串推到向量中,然后使s在最后一个点前所有东西。重复此操作,直到没有点为止,然后将s推入矢量。

这是如何实现的:

#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> split_at_dot(std::string& s) {
  std::vector<std::string> matches;
  size_t pos;
  // while we can find the last dot
  while((pos = s.find_last_of(".")) != -1) {
    // push back everything after the dot
    matches.push_back(s.substr(pos+1));
    // update s to be everything before the dot
    s = s.substr(0, pos);
  }
  // there are no more dots - push back the rest of the string
  matches.push_back(s);
  // return the matches
  return matches;
}
int main() {
  std::string s = "Workspace.SiteNet.Character.Humanoid";
  std::vector<std::string> matches = split_at_dot(s);
  for(auto match: matches) {
    std::cout << match << std::endl;
  }
}

当我在你的输入上运行它时,我得到:

Humanoid
Character
SiteNet
Workspace

请注意,这将反过来给你预期的答案。如果按照这个顺序获取它们真的很重要,那么可以使用std::stack,或者在调用函数后简单地反转std::vector