f********x 发帖数: 2086 | 1 圣诞节前面的
一开始先网上做的题
然后一个印度人电面,题目是写一个iterator,能随时从给的string里返回下一个词。
next,hasNext。
当时刚做完leetcode,水平还很菜,这题要我现在做肯定就秒杀了。唉。 |
f**********t 发帖数: 1001 | 2 //iterator for next word in string
class IterWords {
const string &_s;
size_t _idx;
public:
IterWords(const string &s) : _s(s), _idx(0) {
while (_idx < s.size() && isspace(_s[_idx])) {
++_idx;
}
}
bool hasNext() {
return (_idx != _s.size());
}
string next() {
if (!hasNext()) {
throw exception();
}
size_t right = _idx + 1;
while (right != _s.size() && !isspace(_s[right])) {
++right;
}
string res(_s.begin() + _idx, _s.begin() + right);
while (right != _s.size() && isspace(_s[right])) {
++right;
}
_idx = right;
return res;
}
};
void IterWordsTest() {
string s {"facebook engineering blog "};
IterWords it(s);
while (it.hasNext()) {
cout << it.next() << ' ';
}
cout << "t:IterWordsTest finishedn";
} |
c***t 发帖数: 50 | 3 mark
【在 f**********t 的大作中提到】 : //iterator for next word in string : class IterWords { : const string &_s; : size_t _idx; : public: : IterWords(const string &s) : _s(s), _idx(0) { : while (_idx < s.size() && isspace(_s[_idx])) { : ++_idx; : } : }
|
p*****9 发帖数: 273 | |
m*******g 发帖数: 410 | 5 C++ version:
#include
#include
using namespace std;
int main(){
string line = "test one two three.";
string arr[4];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 4){
ssin >> arr[i];
++i;
}
for(i = 0; i < 4; i++){
cout << arr[i] << endl;
}
}
http://stackoverflow.com/questions/16029324/c-splitting-string- |
m*******g 发帖数: 410 | 6 Java version:
package com.sasoft;
class IterWords {
String _s;
int _idx;
String words[];
public IterWords(String s){
_s=s;
_idx=0;
words=_s.split("\s+");
}
String next()
{
if (_idx
{
String ss=words[_idx];
_idx+=1;
return ss;
}
else
return null;
}
boolean hasNext() {
return (_idx != words.length);
}
public static void main(String[] args) {
String s ="facebook engineering blog ";
IterWords it =new IterWords(s);
while (it.hasNext()) {
System.out.println (it.next());
}
System.out.println( "t:IterWordsTest finishedn");
}
}
http://stackoverflow.com/questions/7899525/how-to-split-a-strin |