Creating Java String Functions in C/C++

Introduction

You all know which string functions are used in Java programming. But in C/C++ you just know only a few string functions. Java class String provides the rich built-in set of string functions, but C/C++ provides onl a few string functions. So the developera must create those functions that are not provided by default string libraries in C/C++.

In this article we will create these functions in Visual Studio. Visual Studio will force you to use _strupr_s() function instead of strupr() function. If you are using other IDE's like Turbo-C++, Code::Blocks or Dev-C++, then you can use simple string functions like strupr(),strlwr(),strstr() stc. In this article we will use predefined string functions to create our own string functions. The following is the list of string functions used in C/C++.
  1. strlen()
  2. _strrev()
  3. _strupr_s()
  4. _strlwr_s()
  5. strcat_s()
  6. strncpy_s()
  7. strstr() etc. 
I am creating a class String having constructor and will define the functions in it and putting these classes in java string functions.h header file. We will also create a Character class for isLetter(),isDigit() etc functions further.
 
Lets Start

Firstly, create a Visual C++ - Console Application project in Visual Studio. Add new item to project java string functions.h header file. Firstly, define the class,
  1. class String  
  2. {  
  3.     char* str;  
  4.   
  5. public:  
  6.     String(char b[])  
  7.     {  
  8.         str = b;  
  9.     }  
  10.   
  11.     void setValue(char b[])  
  12.     {  
  13.         str = b;  
  14.     }  
  15.   
  16.     char* getValue()  
  17.     {  
  18.         return str;  
  19.     }  
  20. };  
Now, let's see the functions.

We will define all these functions inthe  above class. We will use predefined functions for finding length, uppercase, lowercase, concat, reverse etc of the string.
  1. int length()  
  2. {  
  3.     return strlen(str);  
  4. }  
  5.   
  6. char* reverse()  
  7. {  
  8.     return _strrev(str);  
  9. }  
  10.   
  11. char*toUpperCase()  
  12. {  
  13.     char*s = str;  
  14.     _strupr_s(s, strlen(s) + 1);  
  15.   
  16.     return s;  
  17. }  
  18.   
  19. char*toLowerCase()  
  20. {  
  21.     char*s = str;  
  22.     _strlwr_s(s, strlen(s) + 1);  
  23.   
  24.     return s;  
  25. }  
  26.   
  27. char* concat(char s1[], char s2[])  
  28. {  
  29.     strcat_s(s1, strlen(s1) + strlen(s2) + 1, s2);  
  30.   
  31.     return s1;  
  32. }  
  33.   
  34. char charAt(int pos)  
  35. {  
  36.     return str[pos];  
  37. }  
Now let's create that function which are provided in Java.
1] startsWith(): This function takes an argument of char pointer.
This function returns a string of result true or false.you can use bool return type here.
This function matches each character of the string to another string.if it matches then the value of _true is increased by 1,
otherwise _false value is increased by 1.if _true value is not equal to 0 but _false is equal to 0 then result set to true otherwise false.
  1. char* startsWith(char*s)  
  2. {  
  3.     int i = 0;  
  4.     char* result = "false";  
  5.     int _true = 0, _false = 0;  
  6.   
  7.     while (i < strlen(s))  
  8.     {  
  9.         if (str[i] == s[i])  
  10.         {  
  11.             _true++;  
  12.         }  
  13.         if (str[i] != s[i])  
  14.         {  
  15.             _false++;  
  16.         }  
  17.   
  18.         i++;  
  19.     }  
  20.   
  21.     if (_true != 0 && _false == 0)  
  22.     {  
  23.         result = "true";  
  24.     }  
  25.     else if (_false != 0 && _true == 0)  
  26.     {  
  27.         result = "false";  
  28.     }  
  29.     else  
  30.     {  
  31.         result = "false";  
  32.     }  
  33.   
  34.     return result;  
  35. }  
2. endsWith() :

This function takes an argument of char pointer. This function returns a string of result true or false. This function is same as startsWith() function only just change in condition and decreasing the value of i & j.
 
3. equals() :

This function takes an argument of char pointer. This function returns a string of result true or false. If the length of given string is same as default string and all the characters are same then it returns true otherwise false. See equalsIgnoreCase() code only just removing strncpy_s() & _strupr_s() function. 
 
4. equalsIgnoreCase() :

This function takes an argument of char pointer. This function returns a string of result true or false. First changing the case of given two strings to upper case for ignoring the cases of strings. If the length of given string is same as default string and all the characters are same then it returns true otherwise false.
  1. char*equalsIgnoreCase(char*s)  
  2. char*result = "false";  
  3. int str_len = strlen(str);  
  4. int s_len = strlen(s);  
  5. int _true = 0, _false = 0;  
  6. char str2[256] = "";  
  7. char s2[256] = "";  
  8.   
  9. strncpy_s(str2, str, sizeof(str2)-1);  
  10. _strupr_s(str2, strlen(str2) + 1);  
  11. strncpy_s(s2, s, sizeof(s2)-1);  
  12. _strupr_s(s2, strlen(s2) + 1);  
  13.   
  14. str2[strlen(str2)] = '\0';  
  15. s2[strlen(s2)] = '\0';  
  16.   
  17. if (str_len == s_len)  
  18. {  
  19.     int i = 0;  
  20.     while (i < str_len)  
  21.     {  
  22.         if (str2[i] == s2[i])  
  23.         {  
  24.             _true++;  
  25.         }  
  26.         else  
  27.         {  
  28.             _false++;  
  29.         }  
  30.   
  31.         i++;  
  32.     }  
  33.     if (_true != 0 && _false == 0)  
  34.     {  
  35.         result = "true";  
  36.     }  
  37.     else if (_false != 0 && _true == 0)  
  38.     {  
  39.         result = "false";  
  40.     }  
  41.     else  
  42.     {  
  43.         result = "false";  
  44.     }  
  45. }  
  46. else  
  47. {  
  48.     result = "false";  
  49. }  
  50.   
  51.  return result;  
  52. }
5. compareTo():

This function takes an argument of char pointer. This function is same as equals() function(see 3). Only this function returns integer value. Download the source code to view this function. 
 
6. indexOf():
 
This function takes an argument of char pointer. In C/C++, function strstr() returns the further string when the first occurence of the given string is found. But in java,it returns the position of the first occurence of the string in the given string. Position can be calculated by subtracting the length of given string from default string.
  1. int indexOf(char*s)  
  2. {
  3. int str_len = strlen(str);  
  4. int s_len = strlen(s);  
  5. int result = -1;  
  6. char*ss;  
  7. if ((ss = strstr(str, s)) != NULL)  
  8. {  
  9.     int ss_len = strlen(ss);  
  10.     result = str_len - ss_len;  
  11.     ++ss;  
  12. }  
  13.  return result;  
  14. }
  15.                    
7. lastIndexOf():

This function takes an argument of char pointer. It returns the position of the last occurence of the string in the given string. This can be achieved by reversing the string & applying the indexOf() operations on it.
  1. int lastIndexOf(char*s)
  2. {
  3. int str_len = strlen(str);  
  4. int s_len = strlen(s);  
  5. int result = -1;  
  6. char*ss = "";  
  7. char rev_str[256] = "";  
  8. char rev_s[256] = "";  
  9.   
  10. strncpy_s(rev_str, str, sizeof(rev_str)-1);  
  11. _strrev(rev_str);  
  12. strncpy_s(rev_s, s, sizeof(rev_s)-1);  
  13. _strrev(rev_s);  
  14.   
  15. rev_str[strlen(rev_str)] = '\0';  
  16. rev_s[strlen(rev_s)] = '\0';  
  17.   
  18.   
  19. if ((ss = strstr(rev_str, rev_s)) != NULL)  
  20. {  
  21.     int ss_len = strlen(ss);  
  22.     int a = str_len - ss_len;  
  23.     result = str_len - (a + 1);  
  24. }  
  25.   
  26.  return result;  
  27. }
8. substring() :

This function takes an argument of char pointer. This function returns the part of the string from the specific position.
  1. char* substring(int startIndex)
  2. {
  3. char*result = (char*)malloc(sizeof(char)* 100);  
  4. int str_len = strlen(str);  
  5. int i = 0;  
  6.   
  7. if (startIndex > 0)  
  8. {  
  9.     while (i < str_len)  
  10.     {  
  11.         result[i] = str[startIndex + i];  
  12.         i++;  
  13.     }  
  14. }  
  15. result[i] = '\0';  

  16.  return result;
  17. }
Now lets see some character functions provided in java. I am creating a class Character and defining the static functions in it.
  1. class Character  
  2. {  
  3. public:  
  4.   
  5. };   
Lets see some character functions used in java. Define all the following functions in above class.
 
1. isLetter() :

This function takes an argument of char. This function returns true if the given character is an alphabet letter, otherwise returns false.
  1. static char* isLetter(char ch)  
  2. {  
  3.     static char*result = "false";  
  4.   
  5.     for (char c = 'a'; c <= 'z'; c++)  
  6.     {  
  7.         for (char c1 = 'A'; c1 <= 'Z'; c1++)  
  8.         {  
  9.             if (ch == c || ch == c1)  
  10.             {  
  11.                 result = "true";  
  12.             }  
  13.         }  
  14.     }  
  15.   
  16.     return result;  
  17. }  
2. isDigit():

This function takes an argument of char and returns true if given character is digit otherwise returns false.
  1. static char* isDigit(char ch)  
  2. {  
  3.     static char*result = "false";  
  4.   
  5.     for (char c = '0'; c <= '9'; c++)  
  6.     {  
  7.         if (ch == c)  
  8.         {  
  9.             result = "true";  
  10.         }  
  11.     }  
  12.   
  13.     return result;  
  14. }  
3. isUpperCase():

This function takes an argument of char. This function returns true if given character is in uppercase otherwise returns false. isLowerCase() function is same only just change in for loop character values to (a,z).
  1. static char* isUpperCase(char ch)  
  2. {  
  3.     static char*result = "false";  
  4.   
  5.     for (char c = 'A'; c <= 'Z'; c++)  
  6.     {  
  7.         if (ch == c)  
  8.         {  
  9.             result = "true";  
  10.         }  
  11.     }  
  12.   
  13.     return result;  
  14. }  
Example

To use all defined functions in above,you must create the object of String class. Remember you have to pass the array of character value to the constructor. To handle exception in Visual Studio,create the object of class String in following way. So do like this
  1. char mystr[] = "Java Programming";  
  2. String s1(mystr);  
Instead of,
  1. String s1("Java Programming");  
We have defined the static methods in Character class, so those methods can be called without creating the object of Character class. Use like this Character::isLetter('T')
 
Here's my example to implement these all functions. Download the source code.
  1. #include "stdafx.h"  
  2. #include<conio.h>  
  3. #include"javastringfunctions.h"  
  4.   
  5. int _tmain(int argc, _TCHAR* argv[])  
  6. {  
  7.     char mystr[] = "Java Programming";  
  8.     String s1(mystr);  
  9.   
  10.     std::cout << "\t----String class functions----";  
  11.     std::cout << "\n\t1] getValue() = " << s1.getValue();  
  12.     std::cout << "\n\t2] charAt() = " << s1.charAt(5);  
  13.     std::cout << "\n\t3] compareTo() = " << s1.compareTo("java program");  
  14.     std::cout << "\n\t4] endsWith() = " << s1.endsWith("ming");  
  15.     std::cout << "\n\t5] equals() = " << s1.equals("java programming");  
  16.     std::cout << "\n\t6] equalsIgnoreCase() = " << s1.equalsIgnoreCase("JAVA PROGRAMMING");  
  17.     char a[100]="";  
  18.     s1.getChars(1, 14, a);  
  19.     std::cout << "\n\t7] getChars() = " << a;  
  20.   
  21.   
  22.     // change the string using setValue() function  
  23.     s1.setValue("The horse can run faster than human being");  
  24.     std::cout << "\n\n\tNow string is '" << s1.getValue()<<"'";  
  25.     std::cout << "\n\n\t8] indexOf() = " << s1.indexOf("horse");  
  26.     std::cout << "\n\t9] lastIndexOf() = " << s1.lastIndexOf("faster");  
  27.     std::cout << "\n\t10] length() = " << s1.length();  
  28.     std::cout << "\n\t11] replace() = " << s1.replace("horse""dog");  
  29.   
  30.     char mystr2[] = "The Elephant is bigger than ant";  
  31.     String s2(mystr2);  
  32.     std::cout << "\n\n\tNow string is '" << s2.getValue() << "'";  
  33.     std::cout << "\n\n\t12] Reverse() = " << s2.reverse();  
  34.     // reverse the string for further operations  
  35.     s2.reverse();  
  36.   
  37.     std::cout << "\n\t13] startsWith() = " << s2.startsWith("The");  
  38.     std::cout << "\n\t14] substring() = " << s2.substring(13);  
  39.     std::cout << "\n\t15] toLowerCase() = " << s2.toLowerCase();  
  40.     std::cout << "\n\t16] toUpperCase() = " << s2.toUpperCase();  
  41.   
  42.     char mystr3[] = "            C/C++ Programming                 ";  
  43.     String s3(mystr3);  
  44.     std::cout << "\n\n\tNow string is '" << s3.getValue() << "'";  
  45.     std::cout << "\n\n\t17] trim() = " << s3.trim();  
  46.   
  47.     // Character class functions  
  48.     std::cout << "\n\n\t----Character class functions----";  
  49.     std::cout << "\n\t1] isLetter() = " << Character::isLetter('T');  
  50.     std::cout << "\n\t2] isDigit() = " << Character::isDigit('6');  
  51.     std::cout << "\n\t3] isUpperCase() = " << Character::isUpperCase('c');  
  52.     std::cout << "\n\t4] isLowerCase() = " << Character::isLowerCase('W');  
  53.     std::cout << "\n\t5] isWhiteSpace() = " << Character::isWhitespace('c');  
  54.     std::cout << "\n\t   isWhiteSpace() =  " << Character::isWhitespace(' ');  
  55.   
  56.     String s4("C:\\Visual Studio Projects\\My String Functions\\My String Functions\\My String Functions.cpp");  
  57.     std::cout << "\n\n\tFilename = " << s4.substring(s4.lastIndexOf("\\") + 1);  
  58.   
  59.     std::cout << "\n\n\t----External String functions----";  
  60.     char b[] = "Hello";  
  61.     char c[] = "World";  
  62.     std::cout << "\n\ttoUpperCase() = " << Str_toUpperCase(b);  
  63.     std::cout << "\n\treverse() = " << Str_reverse(c);  
  64.     _getch();  
  65.     return 0;  
  66. }  
Here's the output of above program. 
 
  

Read more articles on C/C++:


Similar Articles