fork(3) download
  1. #include <stdio.h>
  2. #include <stddef.h>
  3. #include <ctype.h>
  4.  
  5. #define MAX_STR_LEN 50
  6.  
  7. void to_camel_case(char *str)
  8. {
  9. int idx = 0;
  10. int newIdx = 0;
  11. int wasUnderscore = 0;
  12.  
  13. // just to be on the safe side
  14. if (!str || strlen(str) >= MAX_STR_LEN)
  15. return;
  16.  
  17. while (str[idx])
  18. {
  19. if (str[idx] == '_')
  20. {
  21. idx++;
  22. // no copy in this case, just raise a flag that '_' was met
  23. wasUnderscore = 1;
  24. }
  25. else if (wasUnderscore)
  26. {
  27. // next letter after the '_' should be uppercased
  28. str[newIdx++] = toupper(str[idx++]);
  29. // drop the flag which indicates that '_' was met
  30. wasUnderscore = 0;
  31. }
  32. else
  33. {
  34. // copy the character and increment the indices
  35. str[newIdx++] = str[idx++];
  36. }
  37. }
  38.  
  39. str[newIdx] = '\0';
  40. }
  41.  
  42. int main(void) {
  43.  
  44. char words[][MAX_STR_LEN] = {"hello_world", "hello___world", "hel_lo_wo_rld__", "__hello_world__"};
  45.  
  46. for (int i = 0; i < sizeof(words)/sizeof(words[0]); ++i)
  47. {
  48. printf("String %s became ", words[i]);
  49. to_camel_case(words[i]);
  50. printf("%s\n", words[i]);
  51. }
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
String hello_world became helloWorld
String hello___world became helloWorld
String hel_lo_wo_rld__ became helLoWoRld
String __hello_world__ became HelloWorld