Learn-dsa..in 30 days!



























String Operations

Initializing the String.

Below are some ways to initialize Strings in java:

String str1 = new String(“invoice”);
String str2 = “Payment details”;
String str3 = “”;
String str4=null;

String class has around 10+ constructors that can be used to create and initialize strings. These constructors take char[], int[], byte[] as inputs. We can construct the String using one of these constructors as needed.

The String.valueOf() methods can also be used to get a String formed by the input characters:

String str5=String.valueOf(‘d’):
char[] ch={‘h’,‘e’,‘l’,‘l’,‘o’};
String str6=String.valueOf(ch);

Length of the String.

The length of the String be accessed using the length() function as shown below:

int strLength= str.length();

Searching within a String.

The indexOf() method can be used to search for first occurrence of a char or String within the given String:

String str=”greener”;
int idx1=str.indexOf(‘r’);
int idx2=str.indexOf(“en”);

The lastIndexOf() can be used to search for last occurrence of a char or String within the given String:

int idx3=str.lastIndexOf(‘e’);
int idx4=str.lastiIndexOf(“en”);

The contains() method can also be used to check the occurrence of a char sequence within the given String:

Boolean cnt=str.contains(“green”);

Accessing the String’s characters.

To access particular character in the String in the we use charAt() method. Below we are accessing the char at index 3:

char ch=str.charAt();

To access a sequence of characters between 2 indexes of the String with the String we can use the getChars() method. Below we are accessing the chars of the String between index 2 and 5 and filling the result in char array named dst from index 0:

char[] chars=str.getChars(2, 5, dst, 0);

To get an array of all characters within a String we can use the toCharArray() method:

char[] chars=str.toCharArray();

To get an array of characters within certain indexes of the String, the substring() method can be used:

String str2=str1.substring(4,10);

Replacing characters within a String.

To replace characters within a String we can use the replace() methods:

String str=new String(“Original):
str.replace(‘r’, ‘t’);
str.replace(“al”, “aux’);
str.replaceAll(“ri”, “ra”);

Inserting new characters within a String.

As String class in Java is immutable, there are no methods to directly add chars to an existing String. If a character needs to be added to the original String, a new String is created which concatenates the original String and the new char using “+” operator as shown below:

String str1=”Original”;
Str2=str1+”ly”;

Alternatively, to add one char to end of a String, the following algorithm can be used:

Pseudocode:

The java method should accept following input parameters: str (String), newCh (character to be added).
Extract the characters from str using toCharArray() method into an array named chars1.
Create a new char array chars2 with length 1 more than chars1.
Iterate through chars1 array using a for loop with loop variable names idx:
Set chars2[idx]=chars1[idx]
After above loop completes, set chars2[length-1]=newCh.
Create a new String using chars2 and return the same.

Code:

public String stringAddChar(String str, char newCh) {
	char[] chars1=str.toCharArray();
	char[] chars2=new char[chars1.length+1];
	for (int idx=0; idx < str.length(); idx++) {
		chars2[idx]=chars1[idx];
	}
	chars2[chars2.length-1]=newCh;
	return new String(chars2);
}

Deleting characters within a String.

String class in java is immutable, so there are no methods to directly delete characters from within a String. To delete a character from the String, a new String without the character to be deleted will need to be created. Below code show cases one method of deleting the first instance of input character from a given String.

Pseudocode:

The java method should accept following input parameters: str (String), rem (character to be removed).
If rem does not exist in str, return str as no further processing is required.
Extract the characters from str using toCharArray() method into an array named chars1.
Create a new char array chars2 with length 1 less than chars1.
Iterate through chars1 array using a for loop with loop variable names idx:
If chars2[idx] == rem and if this is the first occurrence of rem, do not add it to chars2.
If chars1[idx] != rem and it is not the first occurrence of rem, add it to chars2.
After above loop completes, create a new String using chars2 and return the same.

Code:

public String stringDeleteChar(String str, char rem) {
	if (str.indexOf(rem)==-1) {
		return str;
	}
	char[] chars1=str.toCharArray();
	char[] chars2=new char[chars1.length-1];
	int chars2Idx=0;
	boolean firstOccDeleted=false;
	for (int idx=0; idx < str.length(); idx++) {
		if ((chars1[idx] == rem)&& (firstOccDeleted==false)) {
			firstOccDeleted=true;
		}else {
			chars2[chars2Idx]=chars1[idx];
			chars2Idx++;
		}
	}
	return new String(chars2);
}

public String stringDeleteCharSb(String str, char rem) {
	char[] chars=str.toCharArray();
	StringBuilder sb=new StringBuilder();
	for (int idx=0; idx < str.length(); idx++) {
		if (str.charAt(idx) != rem) {
			sb.append(str.charAt(idx));
		}
	}
	return sb.toString();
}

StringBuilder and StringBuffer classes.

In addition to String class, Java also provides StringBuilder and StringBuffer classes. StringBuffer is mutable sequence of characters that is safe to be used by multiple threads as the methods are synchronized. Similarly, StringBuilder is also a mutable sequence of characters that is designed to be used if your program uses only one thread. The main methods of StringBuilder and StringBuffer are multiple variants of insert(), append() and delete() operations. If your program requires the Strings to be modified by addition, insertion and deletion of characters, you can consider using StringBuilder or StringBuffer rather than String.