Strings
-----------
A java strings, is not a
character array and is not NULL terminated.
Strings may be declared and created as follows:
String stringname;
stringname=new
String("String");
ex:1
String firstname;
firstname=new
String("Rahul Dravid");
These two statements combined
as follows:
String firstname=new
String("Rahul Dravid");
String Method
Method
·
s2=s1.toLowerCase; Converts the string s1 to all
lowercase
·
s2=s1.toUpperCase; Converts the string s1 to all Uppercase
·
s2=s1.replace('x','y'); Replace all appearances of x with
y
·
s2=s1.trim(); Remove white spaces
at the beginning
and end of the string s1
·
s1.equals(s2) Return 'true' if s1
is equal to s2
·
s1.equalsIgnoreCase(s2); Returns 'true' if s1=s2,
ignoring the
case of characters
·
s1.length() Gives the length
of s1
·
s1.charAt(n) Gives nth
character of s1
·
s1.compareTo(s2) Returns negative if
s1<s2, positive if
s1>s2,and
zero if s1 is equal s2
·
s1.concat(s2) Concatenates s1 and
s2
·
s1.substring(n) Gives substring starting
from nth character
·
s1.substring(n,m) Gives substring starting
from nth
character
up to mth (not including
mth)
·
String.ValueOf(p) Creates a string object of
the
parameter p(simple type or object)
·
p.toString() Creates a string representation of
the object p
·
s1.indexOf('x') Gives the position of the first
occurrence of 'x' in the string
s1
·
s1.indexOf('x',n) Gives the position of 'x' that occurs
after nth position in the string s1
·
String.ValueOf(Variable)
Converts the parameter value to string
representation
The String class supports
several constructors. To create an empty
String, we call the default constructors.
ex:
String s=new String();
ex:
char c[]={'a','b','c','d'};
String s=new String(c);
syntax:
String(char chars[],int
startIndex,int numChars);
String(String strObj);
ex:
char c[]={'a','b','c','d','e','f'};
String s=new String(c,2,3);
ex1:
class str1
{
public static void main(String args[])
{
char c[]={'a','b','c','d','e','f'};
String s1=new String(c);
String s2=new String(s1);
String s=new String(c,2,3);
System.out.println(s1);
System.out.println(s2);
System.out.println(s);
}
}
byte array
--------------
String(byte asciiChars[])
String(byte asciiChars[],int
startIndex,int numChars)
ex:
class str2
{
public static void main(String args[])
{
byte a[]={65,66,67,68,69,70};
String s1=new String(a);
System.out.println(s1);
String s2=new String(a,2,3);
System.out.println(s2);
}
}
It is possible to get the
length of string using the length method of the String class.
Java strings can be
concatenated using the + operator.
class strex1
{
public static void main(String args[])
{
String name=new String("Anil");
System.out.println("Length="+name.length());
System.out.println("hello="+"hello".length());
}
}
String Concatenation with other Data Types
class str3
{
public static void main(String args[])
{
int age=15;
String s="He is "+age+" years
old";
String s1="four :"+2+2;
String s2="Six :"+(3+3);
System.out.println(s);
System.out.println(s1);
System.out.println(s2);
}
}
String Conversion and toString()
syntax:
String toString()
To implement toString(),
simply return a String object.
Program1
class Area
{
int l,b;
Area(int x,int y)
{
l=x;
b=y;
}
public String toString()
{
return "Area is"+(l*b);
}
}
class str4
{
public static void main(String args[])
{
Area a=new Area(10,20);
String s="Rectangle's"+a;
System.out.println(s);
}
}
Program2
class Box{
double width,height,depth;
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
public String toString()
{
return "Dimensions are "+width+" by
"+height +" by "+depth;
}
}
class str5
{
public static void main(String args[])
{
Box b=new Box(10,20,30);
String s="Box b:"+b;
System.out.println(b);
System.out.println(s);
}
}
Character Extraction
---------------------------
The String class provides a
number of ways in which characters can be extracted from a String object.
charAt()
---------
syntax:
char charAt(int where);
class str6
{
public static void main(String args[])
{
char c;
String s="Welcome";
c="abc".charAt(1);
System.out.println("c(1)="+c);
System.out.println(s.charAt(5));
}
}
getChars()
------------
syntax:
void getChars(int sourceStart, int sourceEnd,char
target[],int targetStart)
Ex:
class str7
{
public static void main(String args[])
{
char c;
String s="Hava a Good Day";
int start=7;
int end=15;
char a[]=new char[25];
s.getChars(start,end,a,0);
System.out.println(a);
}
}
getBytes()
-------------
Character to byte Conversion
syntax:
byte[] getBytes()
ex:
class str8
{
public static void main(String args[])
{
char c;
String s="Hava a Good Day";
byte b[]=new byte[s.length()];
b=s.getBytes();
for(int i=0;i<b.length;i++)
System.out.print((char)b[i]);
}
}
String Comparison
------------------------
syntax:
boolean equals(Object str)
boolean
equalsIgnoreCase(String str)
ex:
class str9
{
public static void main(String args[])
{
String s1="Hello";
String s2="Hello";
String s3="Good-bye";
String s4="HELLO";
System.out.println(s1+" equals
"+s2+"->"+s1.equals(s2));
System.out.println(s1+" equals
"+s3+"->"+s1.equals(s3));
System.out.println(s1+" equals
"+s4+"->"+s1.equals(s4));
System.out.println(s1+"
equalsIgnoreCase "+s4+"->"+s1.equalsIgnoreCase(s4));
}
}
equals() Versus ==
-----------------------
class EqulasNotEqualTo
{
public static void main(String args[])
{
String s1="Hello";
String s2=new String(s1);
System.out.println(s1+" equals
"+s2+" -> "+s1.equals(s2));
System.out.println(s1+" equals
"+s2+" -> "+(s1==s2));
}
}
s1 and s2 do not refer to the
same objects.
CompareTo()
------------------
syntax:
int compareTo(String str)
class StringOrdering
{
static String name[]={"Chennai","Delhi ","Ahmedabad","Calcutta ","Bombay "};
public static void main(String args[])
{
int size=name.length;
String temp=null;
for(int i=0;i<size-1;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[i].compareTo(name[j])>0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}
Searching Strings
--------------------
indexOf()
----------
Searches for the first occurrence of a character or
substring
syntax:
int indexOf(int ch)//Searches for the first occurrence of a
character
int indexOf(String str)//Searches for the first occurrence
of a substring
lastindexOf()
-----------------
int lastIndexOf(int
ch)//Searches for the last occurrence of a character
int lastIndexOf(String
str)//Searches for the last occurrence of a
substring
ex :for indexOf() and
lastIndexOf()
--------------------------------------
class indexOfDemo{
public static void main(String args[])
{
String s="Now is the time for all good men to
come to the aid of their country";
System.out.println(s);
System.out.println("indexOf('t')="+s.indexOf('t'));
System.out.println("lastindexOf('t')="+s.lastIndexOf('t'));
System.out.println("indexOf(the)="+s.indexOf("the"));
System.out.println("lastindexOf(the)="+s.lastIndexOf("the"));
}
}
concat()
--------
class concat
{
public static void main(String args[])
{
String s1="one";
String s2=s1.concat("two");
System.out.println(s2);
}
}
replace()
--------
syntax:
String replace(char
original,char replacement);
trim()
-------
whitespace has been removed.
syntax:
String trim();
class usetrim
{
public static void main(String args[])
{
String s="Hello".replace('l','w');
String s1=" Hello World ".trim();
System.out.println(s);
System.out.println(s1);
}
}
Changing the Case of Characters within a String
-------------------------------------------------------------
String toLowerCase()
String toUpperCase()
ex:
class ChangeCase
{
public static void main(String args[])
{
String s="This is a Test";
String upper=s.toUpperCase();
String lower=s.toLowerCase();
System.out.println(upper);
System.out.println(lower);
}
}
Check given string is palindrome or not
import java.io.*;
class palin{
public static void main(String args[])throws IOException
{
int x,j=0;
String s1;
DataInputStream din=new
DataInputStream(System.in);
System.out.println("Enter a String");
s1=din.readLine();
System.out.println(s1);
x=s1.length();
char a[]=new char[x];
for(int i=x-1;i>=0;i--)
{
a[j++]=s1.charAt(i);
}
String s2=new String(a);
System.out.println(s2);
if(s1.equals(s2))
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}
StringBuffer Class
---------------------
While String creates strings
of fixed length, StringBuffer creates strings of flexible length that can be
modified in terms of both length and content.
We can insert characters and substrings in the middle of a string, or
append another string to the end.
Method Task
s1.setCharAt(n,'x') Modifies the nth
character to x
s1.append(s2) Appends the string s2
to s1 at the end
s1.insert(n,s2) Inserts the string s2
at the position n of the string s1
s1.setLength(n) Sets the length of the string s1 to n. If n<s1.
length()
s1 is truncated. If n>s1.length()
zeros are added to s1
StringBuffer Constructor
------------------------------
StringBuffer()//default
size=16
StringBuffer(int size)
StringBuffer(String
str)//"hai"=16+3=19
length() and capacity()
-------------------------
syntax:
int length();
int capacity();
class strbuf1
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer(20);
StringBuffer s3=new StringBuffer("welcome");
System.out.println(s1.length()+"\t"+s1.capacity());
System.out.println(s2.length()+"\t"+s2.capacity());
System.out.println(s3.length()+"\t"+s3.capacity());
}
}
setLength()
------------
syntax:
void setLength(int len)
charAt() and setCharAt()
----------------------------
syntax:
char charAt(int where)
void setCharAt(int where,char ch)
class strbuf2
{
public static void main(String args[])
{
StringBuffer sb=new
StringBuffer("Hello");
System.out.println("buffer before="+sb);
System.out.println("charAt(1)="+sb.charAt(1));
sb.setCharAt(1,'i');
System.out.println(sb);
sb.setLength(2);
System.out.println("After
sb.setLength(2)="+sb);
}
}
//Count the number of vowels
in a given String
class strbuf3
{
public static void main(String args[])
{
StringBuffer sb=new
StringBuffer("welcome");
int i,c=0;
for(i=0;i<sb.length();i++)
{
if(sb.charAt(i)=='a'||sb.charAt(i)=='e'||sb.charAt(i)=='i'||sb.charAt(i)=='o'||sb.charAt(i)=='u')
c++;
}
System.out.println("Nuber of vowels ="+c);
}
}
--------------------------------------------------------------------------
getChars()
-----------
syntax:
void getChars(int sourceStart,int sourceEnd,char
target[],int targetStart)
append()
----------
syntax:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
ex:
class strbuf4
{
public static void main(String args[])
{
StringBuffer s1=new
StringBuffer("Welcome");
System.out.println(s1.append(" To Temple City "));
System.out.println(s1.append( 625002));
StringBuffer s2=new StringBuffer("
TamilNadu");
System.out.println(s1.append(s2));
}
}
insert()
----------
syntax:
StringBuffer insert(int
index,String str)
StringBuffer insert(int
index,char ch)
StringBuffer insert(int
index,Object obj)
class strbuf5
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("I
Java");
s1.insert(2,"like ");
System.out.println(s1);
}
}
-------------
class strbuf6
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("I
India");
s1.insert(2,"love ");
System.out.println(s1);
StringBuffer s2=new StringBuffer("
Ever");
s1.insert(12,s2);
System.out.println(s1);
s1.insert(17,'!');
System.out.println(s1);
}
}
reverse()
-------------
syntax:
StringBuffer reverse()
class strbuf7
{
public static void main(String args[])
{
StringBuffer s1=new
StringBuffer("abcd");
System.out.println(s1);
s1.reverse();
System.out.println(s1);
}
}
delete() and deleteCharAt()
-------------------------------
syntax:
StringBuffer delete(int startIndex,int endIndex)
StringBuffer deleteCharAt(int loc)
class strbuf8
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("This is a
test");
s1.delete(4,7);
System.out.println("After delete :"+s1);
s1.deleteCharAt(0);
System.out.println("After deleteCharAt
:"+s1);
}
}
replace()
----------
StringBuffer replace(int
startIndex,int endIndex,String str)
class strbuf9
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("This is a
test");
s1.replace(5,7,"was");
System.out.println("After replace
:"+s1);
}
}
substring()
--------------
syntax:
String substring(int startIndex)
String substring(int startIndex,int endIndex)
class strbu9
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("Time is
gold");
System.out.println(s1.substring(5));
System.out.println(s1.substring(8,12));
}
}
No comments:
Post a Comment