Strings in C and Java

Loop
6 min readFeb 7, 2023

--

A string is a group of characters that ends with the null character “\0”in C programming. The description of a string is a collection of characters. A string differs from a character array in that it’s finished by the distinctive letter “\0”.

DECLARATIONS OF STRINGS IN C AND JAVA

char str_name[size];                   //in C Lang
String str = "LoopCCEW"; //in Java

Both the new operator and a string literal can be used to produce String Objects. String objects are produced as Immutable objects in both scripts.

INITIALISING A STRING IN C

char str[] = "LOOPCCEW"; // Assigning a String literal without size

char str[50] = "LOOPCCEW"; // Assigning a String literal with predefined size

char str[9] = { 'L','O','O','P','C','C','E','W','\0'}; // Assigning character by character with size

char str[] = { 'L','O','O','P','C','C','E','W','\0'}; //Assigning character by character without size

Taking input from a user in C:

char str[10];
scanf("%s",str);

char str1[10], str2[10];
scanf("%s %s", str1,str2); // two inputs at same time

IN-BUILT METHODS IN C:

String Methods in C
#include <stdio.h>
#include <string.h>

int main () {

char str1[12] = "LOOP"; //intialize the string

char str2[12] = "Cummins";

char str3[12]; //declaration

int len ;

/* copy str1 into str3 */

strcpy(str3, str1);

printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */

strcat( str1, str2);

printf("strcat( str1, str2): %s\n", str1 );

/* total length of str1 after concatenation */

len = strlen(str1);

printf("strlen(str1) : %d\n", len );

/* comparing str1 and str2*/
int compare=strcmp(str1, str2);

if(compare==0)
{
printf("strcmp(str1, str2) : EQUAL ");
}
else
printf("strcmp(str1, str2) : NOT EQUAL ");


return 0;

}
/*
OUTPUT
strcpy( str3, str1) : LOOP
strcat( str1, str2): LOOPCummins
strlen(str1) : 11
strcmp(str1, str2) : NOT EQUAL
*/

STRINGS IN JAVA

A string in Java is a group of characters that’s an object of thejava.lang class. The string class in Java is used to produce and edit strings. A string can not have its value modified after it has been generated. Strings aren’t primitive types in Java( like int, housekeeper, etc). rather, every string is an object of the predefined String class. There are cases of the String class in every string variable.

// Declaring strings in Java

String greeting = "Hello world!"; // String literal

String s1 = new String("Hello world!"); // String Object

IN-BUILT METHODS IN STRING IN JAVA:

Methods: Description

length(): returns the length of the string

contains(): checks whether the string contains a substring

substring(): returns the substring of the string

join(): join the given strings using the delimiter

replace(): replaces the specified old character with the specified new character.

replaceAll(): replaces all sub strings matching the regex pattern

replaceFirst(): replace the first matching sub string

charAt(): returns the character present in the specified location

getBytes(): converts the string to an array of bytes

indexOf(): returns the position of the specified character in the string

compareTo():compares two strings in the dictionary order.

compareToIgnoreCase(): compares 2 strings in dictionary order, ignoring their case.

trim(): removes any leading and trailing whitespaces.

split(): breaks the string into an array of strings

format(): returns a formatted string

toLowerCase(): converts the string to lowercase

toUpperCase(): converts the string to uppercase

valueOf(): returns the string representation of the specified argument

toCharArray(): converts the string to a char array

matches(): checks whether the string matches the given regex

startsWith(): checks if the string begins with the given string

endsWith(): checks if the string ends with the given string

isEmpty(): checks whether a string is empty of not

contentEquals(): checks whether the string is equal to charSequence

SUB-STRINGS:

A sub-string is a subset of characters within a larger string. It is a portion of the original string that starts at a specific index and continues to the end of the string or to another specified index. A sub-string can be extracted from a string using a specific function or by using string slicing notation.

Example:-

Input: Str =”loop”, pos=2, length=3
Output: “oop”

Approach:

  • Create a character array to store the sub-string.
  • Iterate from the given position for the given length to generate the sub-string required.
  • Store each character in the character array.
  • Print the sub-string.
#include <stdio.h>
#include <string.h>

/* Function to get substring from given string */
void substring(char str[], int start, int end, char subStr[]) {
//Calculating the length of substring
int n = end - start + 1;
int i, j;
// looping through the string from start to end and copying the
// characters to subStr
for (i = start, j = 0; i <= end; i++, j++) {
subStr[j] = str[i];
}
//null terminating the substring
subStr[j] = '\0';
}

int main() {
char str[] = "LOOP CCEW";
char subStr[20];
// calling the function to get the substring
substring(str, 4, 7, subStr);
printf("Original string: %s\n", str);
printf("Substring: %s\n", subStr);
return 0;
}
public class Substrings {
public static void main(String[] args) {
String str = "LOOP CCEW";
String subStr = getSubstring(str, 4, 7);
System.out.println("Original string: " + str);
System.out.println("Substring: " + subStr);
}

/* Method to get substring from given string */
public static String getSubstring(String str, int start, int end) {
// using the substring method of String class to get the substring
return str.substring(start, end + 1);
}
}


//OUTPUT
/*Original string: LOOP CCEW
Substring: CCE
*/

SUB-SEQUENCES OF STRING:

A sub-sequence of a string is a sequence of characters that appear in the same order in the original string, but not necessarily consecutively.

Example:-

An example of a sub-sequence in a string would be the characters “eop” in the string “loopccew”. The characters “eop” appear in the same order in the original string, but not consecutively.

Another example would be the characters “cewco” in the same string, “loopccew”. There are many more combinations.

Approach:

  1. Recursion: One approach is to use recursion to generate all possible sub-sequences by including and excluding each character of the string. This approach can be implemented by a function which takes the given string, a starting index and an ending index, and recursively generates all possible sub-sequences by including and excluding each character of the string.
  2. Iteration: Another approach is to use iteration to generate all possible sub-sequences. This can be done by using two nested loops. The outer loop iterates through each character of the string and the inner loop generates all possible sub-sequences for each character.
#include <stdio.h>
#include <string.h>

void printSubsequences(char str[], int start, int end) {
if (start > end) {
printf("%s\n", str);
return;
}
printSubsequences(str, start + 1, end);
char tmp = str[start];
str[start] = '\0';
printSubsequences(str, start + 1, end);
str[start] = tmp;
}

int main() {
char str[] = "abc";
int n = strlen(str);
printSubsequences(str, 0, n - 1);
return 0;
}

Real-Time Applications of Strings:

  1. Spam Detection: Spam Detection Strings can be used to serve as a spam discovery system as the conception of string matching algorithm will be applied then. Spam( unwanted emails) could beget great fiscal loss. All the spam pollutants use the conception of string matching to identify and discard the spam.
  2. Bioinformatics: Strings can be used in the field of Bioinformatics( DNA sequencing). String matching modules can be used to break issues ( problems) regarding inheritable sequences and can be used to find the patterns in DNA.
  3. Intrusion Detection System: Strings can be used in intrusion discovery systems. Packets that contain intrusion related keywords are set up by applying string matching algorithms.
  4. Search Engines: Strings can be used in numerous Search Engine ways. utmost of the data are available on the internet in the form of textual data. Due to the huge quantum of uncategorised textbook data, it becomes really delicate to search a particular content. WebSearch Engine organize the data and to classify the data string matching algorithms are used.

For queries regarding the content, please drop a mail to loop@cumminscollege.in Links for in-depth studying and practice problems are sent via mail to students of the college on the date of publishing of the blog by Loop Club. The content is a part of DSA Bulletins started by Team Loop, to provide thorough knowledge and facilitate the learning of new topics of DSA. We are a group of students who are passionate about CP and DSA and want to create awareness and help students in the above topics.

--

--

Loop
Loop

Written by Loop

Competitive coding club at Cummins College of Engineering, Pune

No responses yet