OPPO筆試 把字符串分隔成逗號分隔成數組 int,string

輸入一串數字字符串,逗號相隔,分成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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章