0% found this document useful (0 votes)
1 views9 pages

Java StringManipulation -SS

The document provides an overview of string manipulation in Java, explaining the definition of strings, how to declare them, and various built-in functions for string operations. It includes examples of Java programs that demonstrate string functions such as charAt, length, equals, substring, and more. Additionally, it covers character manipulation using the Character class and its associated functions.

Uploaded by

Pradyumn Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views9 pages

Java StringManipulation -SS

The document provides an overview of string manipulation in Java, explaining the definition of strings, how to declare them, and various built-in functions for string operations. It includes examples of Java programs that demonstrate string functions such as charAt, length, equals, substring, and more. Additionally, it covers character manipulation using the Character class and its associated functions.

Uploaded by

Pradyumn Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

STRING MANIPULATION

A String is basically an object that represents sequence of char values. An collection of characters (upper or
lower case alphabets, numerals, special characters, spaces etc ) make up a Java string. For example:

String s = “A-BC+D ef45 89%6 5xyz”.

A String is always enclosed in double quotes as shown above. The ‘S’ of String is always capital or upper
case. Strings are represented as objects of String class, which is defined in the package named – java.lang.
That is in a Strings program, this line should be written on the top:

import java.lang.*

Declaring Strings:

The new operator is used to create a String object, or simply saying to declare a String. For example if your
string name is ‘s’, then we will declare as:
String s = new String( );

Remember from Class IX, the usage of the ‘new’ operator. How an object is created:

class_name object_name = new class_name ( );

Here ‘String’ is the class name and the object is ‘s’

The position of each character of a String is numbered. It is called INDEX NUMBER. REMEMBER: The
index numbering starts with zero, and goes on as 1, 2, 3 and so on. So if my String is “ICSE”, then the index
number of I is 0(zero), index number of C is 1, of S is 2, and of E is 3.

For Example we have a String “COMPUTER”. Then Index numbers of its characters is as:

Sometimes INDEX NUMBER is also mentioned as INDEX POSITION.

We need to learn some pre-defined functions which will help us to work with strings easily.

Below is an example of a Java String Program:

Q. Write a program to declare, input a String and just print it out.

Program:

import java.io.*;
import java.util.*;
import java.lang.*;
public class strprog
{
public static void main(String[] args) throws IOException
{
String str =new String();
Scanner sc = new Scanner(System.in);

System.out.print("Enter a String: ");


str = sc.nextLine();

System.out.println( str );
}
}

NOTE: In the below examples, to understand the functions, only the main() block is written.

In class 9, you have studied how a function top line is written. Please revise these terms of
functions : return value, return data type, argument, parameter etc, especially from pages 111 to
115 of your book.

JAVA STRING FUNCTIONS


char charAt( int )
Usage : char ch = s.charAt(5);
Description : It extracts a single character from a string at the specified int index position.
EXTRACT means to pull out.
The line in the above example means: A character at index position 5 is extracted from a String named ‘s’
and is stored in a character variable called ‘ch’.
-------------------------------------------------------------------------------------------------------------------------------------------------------
int length( )
Usage : int len = s.length( );
Description : This function finds the number of ( or count of ) characters present in the
string.
------------------------------------------------------------------------------------------------------------------------------------------------------
Example : This program uses the above two functions – charAt () and length().
Q. Write a program to input your name and print its characters vertically.
It means we have to extract each character of the String, and print them in a fresh line.
Program:
public static void main(String[] args) throws IOException
{
String str =new String();
int x, len;
char ch;

Scanner sc = new Scanner(System.in);

System.out.print("Enter your name: ");


str = sc.nextLine();
len = str.length();
System.out.println();
for ( x = 0 ; x < = len -1; x++ )
{
ch = str.charAt(x);
System.out.println( ch );
}
}

------------------------------------------------------------------------------------------------------------------------------------------------------

Please remember this:

All our programs start as

import java.io.*;
import java.util.*;
public class …………..
{
public static void main(String args[]) throws IOException
{
xxxxx xxxxx xxxxx xxxxx
}
}

But in future I will not write these lines every time (written in blue). It is understood. I will write only the
‘main’ block, the area which is shown above as xxxxx xxxxx xxxxx xxxxx . But you have to write the whole
program every time.

In some of the below functions and programs we have two Strings called ‘s1’ and ‘s2’.

To check if the two Strings are similar, that is if they have the same characters in the same order.

boolean equals( )
Usage : if ( s1.equals(s2) )
Description : This function is used to compare the two strings for similarity. It will also
check if their case is same ie. upper / lower case.
------------------------------------------------------------------------------------------------------------------------------------------------------
boolean equalsIgnoreCase( )
Usage : if ( s1.equalsIgnoreCase (s2) )
Description : This function is used to compare the two strings for similarity, without taking
the case of the Strings into account.
The above two functions will always give a boolean result, that is either true or false. They
are generally used with the if statement.
------------------------------------------------------------------------------------------------------------------------------------------------------
Q.: Write a program to input a word and print whether it is a palindrome or not.
Program:
public static void main(String arg[]) throws IOException
{
String s=new String();
String n=new String();
char ch;
int len, x;
Scanner sc = new Scanner(System.in);

System.out.print("Enter a String: ");


s = sc.nextLine();
len= s.length();
for(x=0; x<= len-1; x++)
{
ch= s.charAt(x);
n=ch+ n;
}
System.out.println("Reverse String is: "+ n);

if(n.equals(s))
System.out.println("\nString is Pallindrome");
else
if(n.equalsIgnoreCase(s))
System.out.println("\nString is Pallindrome if case is Ignored");
else
System.out.println("\nString is NOT Pallindrome");

}
}
------------------------------------------------------------------------------------------------------------------------------------------------------

The substring( ) function works in two variants.


String substring(int )
String substring(int, int )
Usage : String s = s1.substring(5);
String s = s1.substring(5, 7);
Description : This function extracts a series of continuous characters from a
string at the specified int index position to end of String.
If two int positions are given, the extraction starts from the first int position to
one less than the second int index position.
------------------------------------------------------------------------------------------------------------------------------------------------------
Write a program to input a word and print the pattern as shown:
For Example: INPUT : HAPPY
OUTPUT :
H
H A
H A P
H A P P
H A P P Y
Print the above pattern using :
(a) charAt() function
(b) substring() function
SOLUTION :
(a) Program using charAt() function:
import java.io.*;
import java.util.*;
import java.lang.*;
public class strhappychar
{
public static void main(String arg[]) throws IOException
{
String s=new String();
char ch;
int len,x,y;
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter a String: ");
s= sc.next();
len= s.length();
for(x=0; x<=len-1; x++)
{
for(y=0; y<= x; y++)
{
ch= s.charAt(y);
System.out.print(ch);
}
System.out.println();
}
}
}

(b) Program using substring() function:


import java.io.*;
import java.util.*;
import java.lang.*;
public class strhappysubstr
{
public static void main(String arg[]) throws IOException
{
String s=new String();
char ch;
int len,x,y;
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter a String: ");
s= sc.next();
len= s.length();
for(x=1; x<=len; x++)
{
System.out.println(s.substring(0, x));
}
}
}
Above programs will give the output as:
H
H A
H A P
H A P P
H A P P Y
------------------------------------------------------------------------------------------------------------------------------------------------------

String replace( char, char )


Usage : String s = s.replace ( ‘P’, ‘T’ );
Description : This function replaces all occurrences of the first char with the
second char.
---------------------------------------------------------------------------------------------------------------------------
int compareTo( )
Usage : int i = s1.compareTo(s2);
Description : This function is used to compare the two strings lexicographically. That is it
will compare the two Strings and give the result value 0 if the two strings are equal ; a value
less than 0 if this string is lexicographically less than the string argument; and a value greater
than 0 if this string is lexicographically greater than the string argument.
NOTE: This function gives the result as an integer (number).
------------------------------------------------------------------------------------------------------------------------------------------------------

String concat( )
Usage : String s = s1.concat(s2);
Description : This function is used to join two Strings back to back. The + sign
can also be used instead of concat( ).
---------------------------------------------------------------------------------------------------------------------------
Concatenate, concatenation, or concat is a word that is used to combine or
join a string or text end – to – end without any space.
As written above, + sign can be used instead of the concat( ) function.
Try to understand how the + sign works :
For example: If you have two numbers and you write 45 + 78, the + sign will
add the values of the two numbers to give answer as 123.
But, if you have two Strings as “TEXT” and “BOOK”, and you write
“TEXT” + “BOOK”, then the answer will be a new string as “TEXTBOOK”. You
see, the two Strings are joined end to end.
If you write any numerals in double quotes, then it will be treated as String.
eg if you write “123” + “789” the answer will be a new String as “123789”. Here
the values are not added.
eg if you write “456” + “GOOD” the answer will be a new String as “456GOOD”.
---------------------------------------------------------------------------------------------------------------------------
int indexOf( char )
Usage : int i = s.indexOf( ‘ T ’ );
Description : It returns the position of the first occurrence of the character in
the given String.
int indexOf( char, int )
Usage : int i = s.indexOf( ‘T’, 3 );
Description : It returns the position of the first occurrence of the character in
the given String starting the search from the specified int position.
---------------------------------------------------------------------------------------------------------------------------
The indexOf( ) function also works with String as argument just like with char as
argument.
int indexOf( String )
int indexOf(String, int )
---------------------------------------------------------------------------------------------------------------------------
int lastIndexOf( char )
Usage : int i = s.indexOf( ‘T’ );
Description : It returns the position of the last occurrence of the character in
the given String. ( Index position counting always starts from the left side ).
---------------------------------------------------------------------------------------------------------------------------
int lastIndexOf( char, int )
Usage : int i = s.indexOf( ‘T’ );
Description : It returns the position of the last occurrence of the character in
the given String before the specified int position.
---------------------------------------------------------------------------------------------------------------------------
The lastIndexOf( ) function also works with String as argument just like with
char as argument.
int lastIndexOf( String )
int lastIndexOf(String, int ) } Similar to above, but searches for Strings
---------------------------------------------------------------------------------------------------------------------------
String trim( )
Usage : String s = s.trim( );
Description : trim( ) removes all leading and trailing spaces from a string.
Space(s) between words remain as they are.
---------------------------------------------------------------------------------------------------------------------------
String replace( char, char )
Usage : String s = s.replace ( ‘P’, ‘T’ );
Description : This function replaces all occurrences of the first char with the
second char.
---------------------------------------------------------------------------------------------------------------------------
The startsWith( ) function works in two variants.
boolean startsWith( char )
boolean startsWith( String )
Usage : if ( s.startsWith( ‘P’ ) )
OR if ( s.startsWith( “COM” ) )
Description : Checks if the first character of the String is as specified by the
char.
Checks if the first few characters of the String is as specified by the String.
---------------------------------------------------------------------------------------------------------------------------
The endsWith( ) function works in two variants.
boolean endsWith( char )
boolean endsWith( String )
Usage : if ( s.endsWith( ‘P’ ) )
OR if ( s.endsWith( “TER” ) )
Description : Checks if the last character of the String is as specified by the
char.
Checks if the last few characters of the String is as specified by the String.
---------------------------------------------------------------------------------------------------------------------------
String toLowerCase( )
Usage : String s1 = s.toLowerCase( );
Description : Converts all characters of the string to lower case letters, and
returns a new String.
---------------------------------------------------------------------------------------------------------------------------
String toUpperCase()
Usage : String s1 = s.toUpperCase( );
Description : Converts all characters of the string to upper case letters, and
returns a new String.
---------------------------------------------------------------------------------------------------------------------------

JAVA CHARACTER FUNCTIONS


Manipulation of characters in Java, can be done through various classes. Like Character class, String class or
StringBuffer class.

CHARACTER CLASS : These functions of character class operate on a single character.

STRING CLASS : This class represent a group of characters represented in double quotes. The values of String class are
immutable ie. they cannot be modified once they are created.

STRING BUFFER CLASS : StringBuffer class is a class of String where an object of StringBuffer class is mutable ie. they
can be modified as and when required.

FUNCTIONS OF CHARACTER CLASS


These functions are provided in the package java.lang. The functions of this class operate on a single character only.
REMEMBER that each of the following functions should be preceded by the word ‘Character’ and dot.

1. boolean isLetter ( char )


Usage : if ( Character.isLetter( ch ) )
This function checks whether the given character is a letter or not ( upper or lower case ) ie. This function will return
true if ‘ch’ is a letter ( A – Z or a – z ).

2. boolean isDigit ( char )


Usage : if ( Character.isDigit( ch ) )
This function checks whether the given character is a numeral (digit) or not ( 0 – 9 ) ie. This function will return true if
‘ch’ is a digit otherwise will return false.

3. boolean isWhiteSpace ( char )


Usage : if ( Character.isWhiteSpace( ch ) )
This function determines whether the specified character is a whitespace. A whitespace includes space, tab or a new
line.

4. boolean isUpperCase ( char )


Usage : if ( Character.isUpperCase( ch ) )
This function checks whether the given character is a letter of upper case or not ( A - Z ) ie. This function will return
true if ‘ch’ is a upper case letter ( A – Z ) otherwise false

5. boolean isLowerCase ( char )


Usage : if ( Character.isLowerCase( ch ) )
This function checks whether the given character is a letter of lower case or not ( a – z ) ie. This function will return
true if ‘ch’ is a lower case letter ( a – z ) otherwise false

6. boolean isLetterOrDigit ( char )


Usage : if ( Character.isLetterOrDigit( ch ) )
This function checks whether the given character is a letter or a digit or not. ( Letter can be upper or lower case ) ie.
This function will return true if ‘ch’ is a letter ( A – Z or a – z ) or a digit ( 0 – 9 ).

7. char toUpperCase ( char )


Usage : char u = Character.toUpperCase( ch )
This function converts the given character to an upper case letter if it is originally a lower case letter. Upper case
letter remains in upper case.

8. char toLowerCase ( char )


Usage : char p = Character.toLowerCase( ch )
This function converts the given character to a lower case letter if it is originally an upper case letter. Lower case
letter remains in lower case.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy