Check if given one string part of other using wildcards

Please support our C++ advertiser: Intel Parallel Studio Home
vishesh vishesh is offline Offline Apr 6th, 2009, 10:49 pm |
0
The given code snippet checks whether a given string is a part of other string and wildcard are allowed.
Quick reply to this message  
C++ Syntax
  1. // search_pattern.cpp
  2.  
  3.  
  4. /**
  5.   * @app Search substring using wildcards
  6.  * @author vishesh yadav
  7.  * @website http://vishesh.exofire.net
  8.  *
  9.  **/
  10.  
  11.  
  12. #include <iostream>
  13.  
  14.  
  15.  
  16. /**
  17.  * @descp Search 'substr' with wild cards in 'str'
  18.  * @param
  19.  * str : pointer to string in which substr is to be searched
  20.  * substr : pointer to string to be searched, wild card allowed
  21.  
  22.  * @returns true is 'sunstr' is inside 'str', else false
  23.  *
  24.  * @notes
  25.  * in case '*', '?' or '\' chars are part of 'str' use '\' in 'substr'
  26.  * followed by desired character, for not using them as wild cards but
  27.  * as a part of 'str'.
  28.  *
  29.  * @example
  30.  * "vishesh", "*is??h"
  31.  * "*goal??", "\*g??\?*"
  32.  *
  33.  **/
  34.  
  35.  
  36. bool search(const char *str, const char *substr);
  37.  
  38.  
  39. int main(int argc, char* argv[])
  40. {
  41. using namespace std;
  42.  
  43. const int MAX = 25;
  44. char s1[MAX], s2[MAX];
  45.  
  46. cout << "Enter String : ";
  47. cin.getline(s1, MAX);
  48.  
  49. cout << "Enter Search Pattern : ";
  50. cin.getline(s2, MAX);
  51.  
  52.  
  53. if ( search(s1, s2) )
  54. cout << "\n\"" << s2 << "\" " << "found in \"" << s1 << "\"";
  55. else
  56. cout << "\n\"" << s2 << "\" " << "not found in \"" << s1 << "\"";
  57. }
  58.  
  59.  
  60. bool search(const char *str, const char *substr)
  61. {
  62. bool x = false;
  63.  
  64. if ( *substr == 0 )
  65. return true;
  66. else if ( *str == 0 )
  67. return false;
  68. else if ( *substr == '\\' )
  69. return search( str, ++substr );
  70. else if ( *substr == '*' )
  71. {
  72. // try every possible substring of 'str' until satisfied
  73. while ( *str )
  74. if ( x |= search( str++, substr+1 ) )
  75. return true;
  76. return false;
  77. }
  78. else if ( *substr == '?' )
  79. return search( ++str, ++substr );
  80. else if ( *substr == *str )
  81. return search( ++str, ++substr );
  82. else if ( *substr != *str )
  83. return search( ++str, substr ); // to make "she" a part of "vishesh"
  84. else
  85. return false;
  86. return true;
  87. }

Message:


Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC