+ - String: Boundary checking on index and subtring operators
- Ported class Integer from the Gnu libg++ library.
Oct 31, 2019 - Release 0.2
Things to do:
=============
-- String: Boundary checking on index and subtring operators
- String: test cases for numerical conversion
- String: Implement String != regex operator
- String: index and rindex methods with String argument
friend bool operator == (const regex &r, const String &s);
};
+class StringException
+{
+ String message;
+
+public:
+
+ StringException(String m)
+ {
+ message = m;
+ }
+
+ String what()
+ {
+ return message;
+ }
+};
+
#endif /* STRING_H */
/* Substring selection and assignment */
-// TODO: Boundary check
-
substring String::operator()(int start, int len)
{
substring sub;
+ if (start >= strlen(p->s) || start + len >= strlen(p->s))
+ {
+ throw StringException("Substring Out of bounds: ("
+ + String(start) + ", " + String(len) + ")");
+ }
sub.str = this;
sub.start = start;
sub.len = len;
char& String::operator[](int i)
{
+ if (i >= strlen(p->s))
+ {
+ throw StringException("Out of bounds: " + String(i));
+ }
+
return p->s[i];
}
assert(c == 'd');
// Out of bounds
- //c = s1[-1];
- //std::cout << "Seventh character of " << s1 << " char(" << (int)c << ")\n";
+ try
+ {
+ c = s1[-1];
+ std::cout << "Seventh character of " << s1 << " char(" << (int)c << ")\n";
+ }
+ catch (StringException se)
+ {
+ std::cout << "String exception: " << se.what() << "\n";
+ }
//assert(c == 'a');
s1[2] = 'Z';
std::cout << "After \"abcde\"[2] = 'Z' : " << s1 << "\n";
assert(s1 == "abZde");
- s1[5] = 'X';
+ try
+ {
+ s1[5] = 'X';
+ }
+ catch (StringException se)
+ {
+ std::cout << "String exception: " << se.what() << "\n";
+ }
std::cout << "After \"abcde\"[5] = 'X' : " << s1 << "\n";
- //assert(s1 == "abZde");
+ assert(s1 == "abZde");
return 0;
}
The length of "abcde" is 5
First character of abcde 'a'
Fourth character of abcde 'd'
+String exception: Out of bounds: -1
After "abcde"[2] = 'Z' : abZde
+String exception: Out of bounds: 5
After "abcde"[5] = 'X' : abZde
PASS string_basics (exit status: 0)
std::cout << s5 << "\n";
assert(s5 == "abc12345678ijkl");
+ // Select a substring out of bounds
+ try
+ {
+ String s7 = "abcdefghijkl";
+ String s8 = s7(9,5); // s7 = "jkl.."
+
+ std::cout << "The substring (9,5) of " << s7 << " is " << s8 << "\n";
+ }
+ catch (StringException se)
+ {
+ std::cout << "String exception: " << se.what() << "\n";
+ }
+
+ //assert(s2 == "defgh");
+
return 0;
}
Replace substring (3,5) of abcdefghijkl with 12345678 : abc12345678ijkl
Insert "12345678" into "abcdefghijkl" : abc12345678defghijkl
Remove part of "abc12345678defghijkl" : abc12345678ijkl
+String exception: Substring Out of bounds: (9, 5)
PASS string_substring (exit status: 0)