OPPO笔试 把字符串分隔成逗号分隔成数组 int,string

15 篇文章 0 订阅

输入一串数字字符串,逗号相隔,分成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.

同样的函数还有:

atol

Convert string to long integer (function )

atof

Convert string to double (function )

strtol

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值