分割字符串的程序不工作? [英] Program that splits strings isn't working?
问题描述
我创建了一个程序,它将一个字符串拆分为更好的字符串,基于。
例如,我输入字符串
I've created a program that splits a string into, well, more strings, based around a .
So, for instance, say I input the string
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);
}
推荐答案
找到 s
中的最后一个点,将点后的所有内容的子串推入向量,然后使 s
在最后一个点之前。重复此操作,直到没有点,然后将 s
插入向量。
I think it would be easier to find the last dot in s
, push the substring of everything after the dot into the vector, then make s
everything before the last dot. Repeat this until there are no dots, then push s
into the vector.
#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;
}
}
当我在输入上运行它时,
When I run it on your input, I get:
Humanoid
Character
SiteNet
Workspace
请注意,这将给您您预期的答案。如果你真的很重要,你可以使用 std :: stack
或者简单地反转 std :: vector
调用函数后。
Notice that this will give you your expected answers in reverse. If it's really important that you get them in that order you can use a std::stack
or simply reverse the std::vector
after calling the function.
这篇关于分割字符串的程序不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!