输入一串数字字符串,逗号相隔,分成int型;
#include<iostream>
#include <vector>
#include <string.h>
#include<string>
#include<stdlib.h>
using namespace std;
typedef string::size_type sz;
int main()
{
string s;
cin >> s;
string p = ",";
s = s + p;
vector<int> a ;
sz i, pos, len = s.size();
for (i = 0; i < len;i++)
{
pos = s.find(p, i);
if (pos<len)
{
int k = atoi(s.substr(i, pos - i).c_str());//用到atoi函数来转换,substr函数进行分隔
a.push_back(k);
i = pos;
}
}
for (int j:a)
{
cout << j << endl;
}
system("pause");
return 0;
}
int atoi (const char * str);
Convert string to integer
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int
.
同样的函数还有:
Convert string to long integer (function )
Convert string to double (function )
Convert string to long integer (function )
分隔成string:
vector<string> fenge(string a, char c)
{
vector<string> b;
int pos = 0, i, len = a.length();
/* for (i = 0; i < len;i++) //第一种方式
{
if (i == 0 && a[i] == c)
{
pos = i + 1;
}
else if (a[i]==c)
{
b.push_back(a.substr(pos, i - pos));
pos = i + 1;
}
else if (i==len-1)
{
b.push_back(a.substr(pos, i - pos + 1));
}
}*/
/*
for (i = 0; i < len;i++) //第二种方式
{
pos = a.find(c, i);
if (pos < len){
b.push_back((a.substr(i, pos - i)));
i = pos;
}
}
return b;
}
另一种答案:
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
int cmp1(int a, int b)
{
return b<a;
}
//字符串分割函数
vector<int> split(string str, string pattern)
{
string::size_type pos;
vector<int> result;
str += pattern;//扩展字符串以方便操作
int size = str.size();
for (int i = 0; i<size; i++)
{
pos = str.find(pattern, i);
if (pos<size)
{
string s = str.substr(i, pos - i);
int tmp = stoi(s);
result.push_back(tmp);
i = pos + pattern.size() - 1;
}
}
return result;
}
int main1()
{
string str;
int pos;
while (cin >> str >> pos)
{
vector<int> result = split(str, ",");
vector<int> result_sort = result;
sort(result_sort.begin(), result_sort.end(), cmp1);
for (int i = 0; i < result.size(); i++)
{
if (result[i] == result_sort[pos-1])
{
cout << i+1 << endl;
break;
}
}
}
system("pause");
return 0;
}