I often find myself writing quite ugly code when doing string manipulations. The code does what's expected, but I would like to feel satisfied with how it looks as well as it performs. Are there any good books, websites, forums that addresses common string manipulation problems? And how would you code the following example scenarios?
A simple scenario: I have a collection of objects that I want to concatenate the result from a specific method on each object and separate each string with " AND ".
This code would do the trick, but it doesn't give that warm cozy feeling you would get after writing some piece of beautiful code.. ;).
List<MyClass> myColl = ..... // initialize the collection..
StringBuilder sb = new StringBuilder();
bool isFirst = true;
foreach (MyClass obj in myColl) {
if (!isFirst) {
sb.Append(" AND ");
}
isFirst = false;
sb.Append(obj.MyStringBuildingMethod());
}
This would maybe be a nicer way if I would use lambda expressions:
List<MyClass> myColl = ..... // initialize the collection..
string result = String.Join(" AND ", myColl.Select(i => i.MyStringBuildingMethod()).ToArray());
And now a more complex scenario: I want to split a string on a delimiter and then split each part into a key/value. The value is enclosed in single quotes, and if the delimiter is inside the value, we should not split on that. The following code does what it should, but it feels like I have used duct tape or something.. ;)
string csvString = "name='Andersson, Per',country='Sweden',city='Stockholm'";
Dictionary<string, string> keyValues = new Dictionary<string, string>();
bool isInsideQuote = false;
int lastPosition = 0;
for (int i = 0; i < csvString.Length; i++) {
if (csvString[i] == ',' && !isInsideQuote) {
string[] keyValuePair = csvString.Substring(lastPosition, i - lastPosition).Split("=".ToCharArray(), 2);
if (keyValuePair.Length == 2) {
keyValues.Add(keyValuePair[0], keyValuePair[1].TrimStart("'".ToCharArray()).TrimEnd("'".ToCharArray()));
}
lastPosition = i + 1;
}
if (csvString[i] == '\'') {
isInsideQuote = !isInsideQuote;
}
}
string[] lastKeyValuePair = csvString.Substring(lastPosition).Split("=".ToCharArray(), 2);
if (lastKeyValuePair.Length == 2) {
keyValues.Add(lastKeyValuePair[0], lastKeyValuePair[1].TrimStart("'".ToCharArray()).TrimEnd("'".ToCharArray()));
}