-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrings.cpp
More file actions
80 lines (71 loc) · 3.19 KB
/
Copy pathStrings.cpp
File metadata and controls
80 lines (71 loc) · 3.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//Strings.cpp
#include "Strings.h"
namespace sdlUtility {
namespace Strings {
/// Returns the position of the nth occurrence of a character within the specified string.
/** @param Occurrence Parameter to specify which occurrence to find.
@param Character The character to find.
@param String The specified string. */
int FindNthOf(int &Occurrence, char Character, const std::string &String) {
int TargetPosition = -1;
if (FindTotalOf(Character, String) >= Occurrence) {
int LastOccurence = -1;
int Counter = 0;
bool More = true;
while (More) {
int Position = String.find(Character, LastOccurence+1);
if (Position >= 0) {
LastOccurence = Position;
Counter++;
if (Counter-1 == Occurrence) {
Occurrence = Position;
More = false;
}
} else More = false;
if (Counter == Occurrence) {
if (Position < 0) Occurrence = -1; else TargetPosition = Position;
}
}
}
return TargetPosition;
}
/// Returns the total occurrences of a character within the specified string.
/** @param Character The character to find.
@param String The specified string. */
int FindTotalOf(char Character, const std::string &String) {
int Counter = 0;
int LastOccurence = -1;
bool More = true;
while (More) {
int Position = String.find(Character, LastOccurence+1);
if (Position >= 0) {
LastOccurence = Position;
Counter++;
} else More = false;
}
return Counter;
}
/// Returns a substring from a character-delimited string, as specified by the parameters.
/** @param String The character-delimited string.
@param Separator Optional delimiter character.
@param SubstringNumber Optional index of the requested substring within the character-delimited string. */
std::string Separate(const std::string &String, char Separator, int SubstringNumber) {
std::string Substring = "";
if (Separator) {
int InitialPosition = 0;
int FinalPosition = 0;
if (SubstringNumber) {
InitialPosition = FindNthOf(SubstringNumber, Separator, String)+1;
if (InitialPosition != 0) FinalPosition = SubstringNumber;
} else {
InitialPosition = 0;
FinalPosition = String.find_first_of(Separator);
}
//std::cout << "(" << InitialPosition << ", " << FinalPosition << ")" << std::endl;
Substring = String.substr(InitialPosition, FinalPosition-InitialPosition);
} else Substring = String;
//std::cout << Substring << std::endl;
return Substring;
}
}
}