StringUtil.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * StringUtil.h
  3. * Copyright © 2012 kbinani
  4. *
  5. * This file is part of vConnect-STAND.
  6. *
  7. * vConnect-STAND is free software; you can redistribute it and/or
  8. * modify it under the terms of the GPL License.
  9. *
  10. * vConnect-STAND is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. */
  14. #ifndef __StringUtil_h__
  15. #define __StringUtil_h__
  16. #include <vector>
  17. #include <string>
  18. using namespace std;
  19. namespace vconnect
  20. {
  21. /**
  22. * 文字列関連のユーティリティ
  23. */
  24. class StringUtil
  25. {
  26. public:
  27. /**
  28. * 文字列を区切り文字で分割する
  29. * @param delimiter 区切り文字
  30. * @param text 文字列
  31. * @param limit 区切る回数の最大値
  32. * @return 区切られた文字列のリスト
  33. */
  34. static vector<string> explode( string delimiter, string text, string::size_type limit = string::npos )
  35. {
  36. vector<string> result;
  37. string::size_type searchFrom = 0;
  38. string::size_type delimiterIndex = text.find( delimiter, searchFrom );
  39. while( delimiterIndex != string::npos ){
  40. string token = text.substr( searchFrom, delimiterIndex - searchFrom );
  41. result.push_back( token );
  42. searchFrom = delimiterIndex + delimiter.length();
  43. if( result.size() + 1 == limit ){
  44. break;
  45. }
  46. delimiterIndex = text.find( delimiter, searchFrom );
  47. }
  48. result.push_back( text.substr( searchFrom ) );
  49. return result;
  50. }
  51. /**
  52. * 含まれる文字列を全て置換する
  53. * @param text 処理対象の文字列
  54. * @param search 検索する文字列
  55. * @param replace 置換する文字列
  56. * @return 置換後の文字列
  57. */
  58. static string replace( string text, string search, string replace )
  59. {
  60. if( search == replace ){
  61. return text;
  62. }
  63. string result = text;
  64. string::size_type index = result.find( search, 0 );
  65. int searchLength = search.length();
  66. int replaceLength = replace.length();
  67. while( string::npos != index ){
  68. result.replace( index, searchLength, replace );
  69. index = result.find( search, index - searchLength + replaceLength + 1 );
  70. }
  71. return result;
  72. }
  73. private:
  74. StringUtil()
  75. {
  76. }
  77. };
  78. }
  79. #endif