Subversion Repositories gelsvn

Rev

Rev 375 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
595 jab 1
/* ----------------------------------------------------------------------- *
2
 * This file is part of GEL, http://www.imm.dtu.dk/GEL
3
 * Copyright (C) the authors and DTU Informatics
4
 * For license and list of authors, see ../../doc/intro.pdf
5
 * ----------------------------------------------------------------------- */
6
 
375 jrf 7
#include <string>
8
#include <list>
9
#include "string_utils.h"
10
 
11
using namespace std;
12
 
13
namespace Util
14
{
15
  string trim(const string& s, const string& wspaces)
16
  {
17
    int front = 0;
18
    int back = static_cast<int>(s.size() - 1);
19
    if(back < front)
20
      return string("");
21
 
22
    while(wspaces.find(s[front]) != wspaces.npos) ++front;
23
    while(wspaces.find(s[back]) != wspaces.npos) --back;
24
    int n = back - front + 1;
25
    if(n < 1)
26
      return string("");
27
    else
28
      return s.substr(front, n);    
29
  }
30
 
31
  string trim(const string& s)
32
  {
33
    return trim(s, " \t\n\r");
34
  }
35
 
36
  void split(const string& s, list<string>& result, const string& delim)
37
  {
38
    size_t begin = 0;
39
    size_t end = s.find(delim);
40
    while(end != s.npos)
41
    {
42
      result.push_back(s.substr(begin, end - begin));
43
      begin = end + delim.size();
44
      end = s.find(delim, begin);
45
    }
46
    if(s.size() > begin)
47
      result.push_back(s.substr(begin, s.size() - begin));    
48
  }
49
 
50
  void split(const string& s, list<string>& result)
51
  {
52
    return split(s, result, " ");
53
  }
54
 
55
  void trim_split(const string& s, list<string>& result, const string& delim)
56
  {
57
    size_t begin = 0;
58
    size_t end = s.find(delim);
59
    while(end != s.npos)
60
    {
61
      result.push_back(trim(s.substr(begin, end - begin)));
62
      begin = end + delim.size();
63
      end = s.find(delim, begin);
64
    }
65
    if(s.size() > begin)
66
      result.push_back(trim(s.substr(begin, s.size() - begin)));
67
  }
68
 
69
  void trim_split(const string& s, list<string>& result)
70
  {
71
    trim_split(s, result, " ");
72
  }
73
 
74
  void get_first(string& s, string& first)
75
  {
76
    size_t pos = s.find(" ");
77
    first = s.substr(0, pos);
78
    if(pos == s.npos)
79
      s = "";
80
    else
81
      s.erase(0, pos + 1);
82
  }
83
 
84
  void get_last(string& s, string& last)
85
  {
86
    size_t pos = s.rfind(" ");
87
    last = s.substr(pos + 1);
88
    if(pos == s.npos)
89
      s = "";
90
    else
91
      s.erase(pos + 1);
92
  }
93
}