Write Strings

Strings: String manipulation is the most common part of many java programs. Strings represent a sequence of characters....

Strings:

String manipulation is the most common part of many java programs. Strings represent a sequence of characters.

In java strings are class objects and implemented using two classes namely string and string buffer. A java string is an instantiated object of the string class. A java string is not a character array and is not null terminated.

Strings may be declared and created as follows. 

string

Ex:

String first name;
First name=new string(“anil”);

These two statements may be combined as follows:

String first name=new string (“anil”);

Like arrays, it is possible to get the length of string using the length method of the string class

int m=first name.length( );

note the use of parentheses here java strings can be concatenated using the + operator.

Ex:

String fullName=name1+name 2;
String city1=”new”+”delhi”;

Whre name 1 and name 2 are java strings containing string constants. Another examples

System.out.println(first name+”kumar”);

String arrays:

We can also create and use arrays that contain strings . the statement
String itemArray[ ]=new string[3];

Will create an item array of size 3 to hold there string constants. We can assign the string to the item array element by element using there different statements or more efficiently using a for loop.

String methods:

The string class defines a number of methods that allow us to accomplish a variety of string manipulation tasks. Lists some of the most commonly used string methods, and their tasks.
Some commonly used string methods:

Method call
Task performed
S2=s1.tolowercase;
S2=s1.touppercase;
S2=s1.replace(‘x’,’y’);
S2=s1.trim( );

S1.equals(s2)
S1.equalsIgnoreCase(s2)

S1.length( )
S1.charAt(n)
S1.compareTo(s2)


S1.concat(s2)
S1.substring(n)

S1.substring(n, m)

String. value of (p)

p. toString( )

s1.indexof(‘x)

s1.indexof(‘x’, n)
string. valueof(variable)
Converts the string s1 to all lowercase
Converts the string s1 to all uppercase
Replace all appearances of x with y
Remove white spaces  at the beginning and end of the string s1
Returns ‘true’ if s1 is equal to s2
Returns ‘true’if s1=s2, ignoring the case of characters
Gives the length of s1
Gives nth character of s1
Returns negative if s1s2, and zero if s1 is equal to concatenates s1 and s2
Gives substring starting from nth character
Gives substring starting nth character up to mth (not including m)
Gives a string object of the parameter p(simple type of object)
Creates a string representation  of the object p
Gives the position of the first occurrence of ‘x’ in the string s1
Gives the position of ‘x’ that occurs after nth position in the string s1
Converts the parameter value to string representation


Post a Comment

emo-but-icon

item