Simple String Examples in Java

In this class, We discuss Simple String Examples in Java.

The reader should have prior knowledge of string methods in Java. Click Here.

Example 1:

Write a Java program to remove a character from the given position in a string.

Code:

class test

{

public static void main(String args[])

{

String s1 = “Java is Top”;

int position = 5;

s1 = s1.substring(0,position) + s1.substring(position+1);

System.out.println(s1);

}

}

Output:

Java s Top

In the above example, we use substring method to break the string.

We break the string into two parts.

One part is the substring before the position, and the second is after the position.

We use the operator “+” in Java to concatenate the two strings.

Example 2:

Write a Java program to count the number of spaces in the given string.

Code:

class test

{

public static void main(String args[])

{

String s1 = “Java is Top”;

char a[] = s1.toCharArray();

int i, count=0;

for(i=0;i<a.length;i++)

{

if(a[i]=’ ‘)

{

count++;

}

}

System.out.println(count);

}

}

We use the “toCharArray()” method to convert the string to an array of characters.

Once we convert to an array of characters, we take one-by-one and check for space.

Whenever we find space, we increment the count.