Guest User

Is there a way to convert C-format strings for C# -format strings in C#/.NET 2.0

a guest
Feb 22nd, 2012
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. "Bloke %s drank %5.2f litres of booze and ate %d bananas"
  2.  
  3. "Bloke {0} drank {1,5:f2} litres of booze and ate {2} bananas"
  4.  
  5. #include <string.h>
  6.  
  7. void convertCtoCSharpFormat(char *dst, const char *src) {
  8. int k1 = 0, k2 = 0;
  9. while (*src) {
  10. while (*src && (*src != '%')) *dst++ = *src++;
  11. if (*src == '%') {
  12. const char *percent;
  13. src++;
  14. if (*src == '%') { *dst++ = '%'; continue; }
  15. if (*src == 0) { /* error: unmatched % */; *dst = 0; return; }
  16. percent = src;
  17. /* ignore everything between the % and the conversion specifier */
  18. while (!strchr("diouxXeEfFgGaAcpsn", *src)) src++;
  19.  
  20. /* replace with {k} */
  21. *dst++ = '{';
  22. if (k2) *dst++ = k2 + '0';
  23. *dst++ = k1++ + '0';
  24. if (k1 == 10) { k2++; k1 = 0; }
  25. /* *src has the conversion specifier if needed */
  26. /* percent points to the initial character of the conversion directive */
  27. if (*src == 'f') {
  28. *dst++ = ',';
  29. while (*percent != 'f') *dst++ = *percent++;
  30. }
  31. *dst++ = '}';
  32. src++;
  33. }
  34. }
  35. *dst = 0;
  36. }
  37.  
  38. #ifdef TEST
  39. #include <stdio.h>
  40. int main(void) {
  41. char test[] = "Bloke %s drank %5.2f litres of booze and ate %d bananas";
  42. char out[1000];
  43.  
  44. convertCtoCSharpFormat(out, test);
  45. printf("C fprintf string: %snC# format string: %sn", test, out);
  46. return 0;
  47. }
  48. #endif
  49.  
  50. StringBuilder cString = new StringBuilder("Bloke %s drank %5.2f litres of booze and ate %d bananas");
  51. cString.Replace("%s","{0}");
  52. cString.Replace("%5.2f", "1,5:f2"); // I am unsure of this format specifier
  53. cString.Replace("%d", "{2}");
  54.  
  55. string newString = String.Format(cString.ToString(), var1, var2, var3);
Add Comment
Please, Sign In to add comment