NSIndexPath *indexPath = [tableView indexPathForSelectedRow];
даст вам NSIndexPath
для текущей выбранной строки. Затем вы можете сделать
[tableView selectRowAtIndexPath:indexPath
animated:NO
scrollPosition:UITableViewScrollPositionMiddle];
, чтобы выбрать эту строку (и показать ее в середине экрана) позже.
Вот моя первая попытка сделать это с использованием векторов и строк:
vector<string> explode(const string& str, const char& ch) {
string next;
vector<string> result;
// For each character in the string
for (string::const_iterator it = str.begin(); it != str.end(); it++) {
// If we've hit the terminal character
if (*it == ch) {
// If we have some characters accumulated
if (!next.empty()) {
// Add them to the result vector
result.push_back(next);
next.clear();
}
} else {
// Accumulate the next character into the sequence
next += *it;
}
}
if (!next.empty())
result.push_back(next);
return result;
}
Надеюсь, это даст вам какое-то представление о том, как это сделать. В строке вашего примера он возвращает правильные результаты с этим тестовым кодом:
int main (int, char const **) {
std::string blah = "___this_ is__ th_e str__ing we__ will use__";
std::vector<std::string> result = explode(blah, '_');
for (size_t i = 0; i < result.size(); i++) {
cout << "\"" << result[i] << "\"" << endl;
}
return 0;
}
Использование STL (извините, компилятор не протестирован)
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::vector<std::string> result;
std::string str = "___this_ is__ th_e str__ing we__ will use__";
std::stringstream data(str);
std::string line;
while(std::getline(data,line,'_'))
{
result.push_back(line); // Note: You may get a couple of blank lines
// When multiple underscores are beside each other.
}
}
// или определите токен
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
#include <sstream>
struct Token: public std::string // Yes I know this is nasty.
{ // But it is just to demosntrate the principle.
};
std::istream& operator>>(std::istream& s,Token& t)
{
std::getline(s,t,'_');
// ***
// Remove extra '_' characters from the stream.
char c;
while(s && ((c = s.get()) != '_')) {/*Do Nothing*/}
if (s)
{
s.unget(); // Put back the last char as it is not '_'
}
return s;
}
int main()
{
std::vector<std::string> result;
std::string str = "___this_ is__ th_e str__ing we__ will use__";
std::stringstream data(str);
std::copy(std::istream_iterator<Token>(data),
std::istream_iterator<Token>()
std::back_inserter(result)
);
}
Вы можете использовать вектор строки (std :: vector
), добавить к нему каждый токен с помощью push_back, а затем вернуть его из своего функция токенизации.
Используйте std :: vector в качестве динамического массива и верните его в качестве результата.
Возможно, вам следует использовать список вместо массива. Таким образом, вам не нужно будет заранее знать количество элементов. Вы также можете рассмотреть возможность использования контейнеров STL.
Если вы настаиваете на создании stringArray
массива в отличие от std :: vector <>
(что было бы правильным) вам нужно либо:
Использовать вектор проще vector :: push_back ()
добавляет новый прочее до конца. Итак:
vector* explode(string s){
vector<string> *v = new vector<string>
//...
// in a loop
v->push_back(string_fragment);
//...
return v;
}
В конце концов, не требуется Осталось для полноты.
Чтобы вернуть массив строк, вы используете char **
.
Как в
char ** explode(const char *in){
...
}
BTW - Как будет ли вызывающая функция знать, сколько элементов в возвращаемом массиве? Вам тоже придется решить это. Используйте std :: vector <>
, если вас не сдерживают внешние силы ...
Подождите, пока ваш класс структур данных, а затем код это со связанным списком. Если это домашнее задание, вы можете обойтись простым начальным массивом очень большого размера.
Код ниже:
template <typename OutputIterator>
int explode(const string &s, const char c, OutputIterator output) {
stringstream data(s);
string line;
int i=0;
while(std::getline(data,line,c)) { *output++ = line; i++; }
return i;
}
int main(...) {
string test="H:AMBV4:2:182.45:182.45:182.45:182.45:182.41:32:17700:3229365:201008121711:0";
cout << test << endl;
vector<string> event;
**This is the main call**
int evts = explode(test,':', back_inserter(event));
for (int k=0; k<evts; k++)
cout << event[k] << "~";
cout << endl;
}
Выходы
H:AMBV4:2:182.45:182.45:182.45:182.45:182.41:32:17700:3229365:201008121711:0
H~AMBV4~2~182.45~182.45~182.45~182.45~182.41~32~17700~3229365~201008121711~0~