new method: makeStringSafeForPropertyName, replaces invalid chars
This commit is contained in:
parent
888a0a8ed5
commit
5f1ca6b556
@ -267,6 +267,38 @@ namespace simgear {
|
||||
return do_strip( s, BOTHSTRIP );
|
||||
}
|
||||
|
||||
string makeStringSafeForPropertyName(const std::string& str)
|
||||
{
|
||||
// This function replaces all characters in 'str' that are not
|
||||
// alphanumeric or '-'.
|
||||
// TODO: make the function multibyte safe.
|
||||
string res = str;
|
||||
|
||||
int index = 0;
|
||||
for (char& c : res) {
|
||||
if (!std::isalpha(c) && !std::isdigit(c) && c != '-') {
|
||||
switch (c) {
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\n':
|
||||
case '\r':
|
||||
case '_':
|
||||
case '.':
|
||||
case '/':
|
||||
case '\\':
|
||||
res[index] = '-';
|
||||
break;
|
||||
default:
|
||||
res[index] = '_';
|
||||
SG_LOG(SG_GENERAL, SG_WARN, "makeStringSafeForPropertyName: Modified '" << str << "' to '" << res << "'");
|
||||
}
|
||||
}
|
||||
index++;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
void
|
||||
stripTrailingNewlines_inplace(string& s)
|
||||
{
|
||||
|
@ -75,7 +75,9 @@ namespace simgear {
|
||||
std::string rstrip( const std::string& s );
|
||||
std::string strip( const std::string& s );
|
||||
|
||||
/**
|
||||
std::string makeStringSafeForPropertyName(const std::string& str);
|
||||
|
||||
/**
|
||||
* Return a new string with any trailing \\r and \\n characters removed.
|
||||
* Typically useful to clean a CR-terminated line obtained from
|
||||
* std::getline() which, upon reading CRLF (\\r\\n), discards the Line
|
||||
|
@ -737,6 +737,11 @@ void testDecodeHex()
|
||||
SG_VERIFY(decoded == data1);
|
||||
}
|
||||
|
||||
void test_makeStringSafeForPropertyName()
|
||||
{
|
||||
SG_CHECK_EQUAL(strutils::makeStringSafeForPropertyName(" ABC/01234\t:\\\"_*$"), "-ABC-01234-_-_-__");
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
test_strip();
|
||||
@ -761,6 +766,7 @@ int main(int argc, char* argv[])
|
||||
test_formatGeod();
|
||||
test_iequals();
|
||||
testDecodeHex();
|
||||
|
||||
test_makeStringSafeForPropertyName();
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user