我正在尝试编写一个程序来分割数字和单词。代码完成,它可以工作。我只是想知道如何在输出结束时删除逗号。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
vector<string> split(string targer, string delimiter);
int main()
{
string s, delimiter;
vector<string> tokens;
cout << "Enter string to spilt:" << endl;
getline (cin,s);
cout << "Enter delimiter string:" << endl;
getline (cin,delimiter);
tokens = split(s, delimiter);
cout << "The substrings are: ";
for(int i = 0; i < tokens.size(); i++)
{
cout << "\"" << tokens[i] << "\"" << "," << " ";
}
cout<<endl;
return 0;
}
vector<string> split(string target, string delimiter){
stringstream ss(target);
string item;
vector<string> tokens;
while (getline(ss, item, delimiter.at(0))) {
tokens.push_back(item);
}
return tokens;
}
答案 0 :(得分:4)
您可以为其添加if
条件:
for(int i = 0; i < tokens.size(); i++)
{
if (i != 0) cout << "," << " ";
cout << "\"" << tokens[i] << "\"";
}
或
string dlmtr = "";
for(int i = 0; i < tokens.size(); i++)
{
cout << dlmtr << "\"" << tokens[i] << "\"";
dlmtr = ", ";
}
答案 1 :(得分:1)
尝试在cout
循环之外输出最后一个for
语句,如下所示:
以前的代码:
for(int i = 0; i < tokens.size(); i++)
{
cout << "\"" << tokens[i] << "\"" << "," << " ";
}
cout<<endl;
新代码:
for(int i = 0; i < tokens.size() - 1; i++)
{
cout << "\"" << tokens[i] << "\"" << "," << " ";
}
if (tokens.size() != 0)
cout << "\"" << tokens[tokens.size() - 1] << "\"";
cout<<endl;
答案 2 :(得分:1)
for(int i = 0; i < tokens.size(); i++)
{
if (i > 0)
cout << ", ";
cout << '"' << tokens[i] << '"';
}
答案 3 :(得分:0)
size_t i = 0;
for(; i < tokens.size() - 1; i++) {
cout << "\"" << tokens[i] << "\"" << "," << " ";
}
if (tokens.size() - 1 >= 0 ) {
cout << "\"" << tokens[i] << "\"";
}
答案 4 :(得分:0)
如何使用退格\b
逃避性格?
在for循环之外,添加此ASCII字符。