Skip to content
This repository
Browse code

fix handling the first and last

  • Loading branch information...
commit e6249eba32618d61fefcefd1b2662157c8c0efed 1 parent 9dca22f
Kurt Schwehr authored October 31, 2012

Showing 1 changed file with 12 additions and 6 deletions. Show diff stats Hide diff stats

  1. 18  ais.cpp
18  ais.cpp
... ...
@@ -1,11 +1,17 @@
1 1
 #include "ais.h"
2 2
 
3 3
 const string nth_field(const string &str, const size_t n, const char c) {
4  
-  // TODO(schwehr): handle the off the end case better
5  
-  size_t pos;
6  
-  size_t count;
7  
-  for (pos = 0, count = 0; count < n && pos != string::npos; count+=1) {
8  
-    if (pos > 0) pos += 1;  // Skip past the current char that matched
  4
+  if (!n) {
  5
+    const size_t pos = str.find(c);
  6
+    cerr << "pos: " << pos << "\n";
  7
+    if (pos == string::npos)
  8
+      return string("");
  9
+    return str.substr(0, pos);
  10
+  }
  11
+
  12
+  size_t pos = 0;
  13
+  for (size_t count = 0; count < n && pos != string::npos; count++) {
  14
+    if (pos > 0) pos += 1;
9 15
     pos = str.find(c, pos);
10 16
   }
11 17
   if (string::npos == pos)
@@ -14,7 +20,7 @@ const string nth_field(const string &str, const size_t n, const char c) {
14 20
   const size_t start = pos;
15 21
   const size_t end = str.find(c, pos+1);
16 22
   if (string::npos == end)
17  
-    return str.substr(start);
  23
+    return str.substr(start+1);
18 24
   return str.substr(start+1, end-start-1);
19 25
 }
20 26
 

0 notes on commit e6249eb

Please sign in to comment.
Something went wrong with that request. Please try again.