Sunday, April 1, 2012

Strings - Java


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

Slider

Image Slider By engineerportal.blogspot.in The slide is a linking image  Welcome to Engineer Portal... #htmlcaption

Tamil Short Film Laptaap

Tamil Short Film Laptaap
Laptapp

Labels

About Blogging (1) Advance Data Structure (2) ADVANCED COMPUTER ARCHITECTURE (4) Advanced Database (4) ADVANCED DATABASE TECHNOLOGY (4) ADVANCED JAVA PROGRAMMING (1) ADVANCED OPERATING SYSTEMS (3) ADVANCED OPERATING SYSTEMS LAB (2) Agriculture and Technology (1) Analag and Digital Communication (1) Android (1) Applet (1) ARTIFICIAL INTELLIGENCE (3) aspiration 2020 (3) assignment cse (12) AT (1) AT - key (1) Attacker World (6) Basic Electrical Engineering (1) C (1) C Aptitude (20) C Program (87) C# AND .NET FRAMEWORK (11) C++ (1) Calculator (1) Chemistry (1) Cloud Computing Lab (1) Compiler Design (8) Computer Graphics Lab (31) COMPUTER GRAPHICS LABORATORY (1) COMPUTER GRAPHICS Theory (1) COMPUTER NETWORKS (3) computer organisation and architecture (1) Course Plan (2) Cricket (1) cryptography and network security (3) CS 810 (2) cse syllabus (29) Cyberoam (1) Data Mining Techniques (5) Data structures (3) DATA WAREHOUSING AND DATA MINING (4) DATABASE MANAGEMENT SYSTEMS (8) DBMS Lab (11) Design and Analysis Algorithm CS 41 (1) Design and Management of Computer Networks (2) Development in Transportation (1) Digital Principles and System Design (1) Digital Signal Processing (15) DISCRETE MATHEMATICS (1) dos box (1) Download (1) ebooks (11) electronic circuits and electron devices (1) Embedded Software Development (4) Embedded systems lab (4) Embedded systems theory (1) Engineer Portal (1) ENGINEERING ECONOMICS AND FINANCIAL ACCOUNTING (5) ENGINEERING PHYSICS (1) english lab (7) Entertainment (1) Facebook (2) fact (31) FUNDAMENTALS OF COMPUTING AND PROGRAMMING (3) Gate (3) General (3) gitlab (1) Global warming (1) GRAPH THEORY (1) Grid Computing (11) hacking (4) HIGH SPEED NETWORKS (1) Horizon (1) III year (1) INFORMATION SECURITY (1) Installation (1) INTELLECTUAL PROPERTY RIGHTS (IPR) (1) Internal Test (13) internet programming lab (20) IPL (1) Java (38) java lab (1) Java Programs (28) jdbc (1) jsp (1) KNOWLEDGE MANAGEMENT (1) lab syllabus (4) MATHEMATICS (3) Mechanical Engineering (1) Microprocessor and Microcontroller (1) Microprocessor and Microcontroller lab (11) migration (1) Mini Projects (1) MOBILE AND PERVASIVE COMPUTING (15) MOBILE COMPUTING (1) Multicore Architecute (1) MULTICORE PROGRAMMING (2) Multiprocessor Programming (2) NANOTECHNOLOGY (1) NATURAL LANGUAGE PROCESSING (1) NETWORK PROGRAMMING AND MANAGEMENT (1) NETWORKPROGNMGMNT (1) networks lab (16) News (14) Nova (1) NUMERICAL METHODS (2) Object Oriented Programming (1) ooad lab (6) ooad theory (9) OPEN SOURCE LAB (22) openGL (10) Openstack (1) Operating System CS45 (2) operating systems lab (20) other (4) parallel computing (1) parallel processing (1) PARALLEL PROGRAMMING (1) Parallel Programming Paradigms (4) Perl (1) Placement (3) Placement - Interview Questions (64) PRINCIPLES OF COMMUNICATION (1) PROBABILITY AND QUEUING THEORY (3) PROGRAMMING PARADIGMS (1) Python (3) Question Bank (1) question of the day (8) Question Paper (13) Question Paper and Answer Key (3) Railway Airport and Harbor (1) REAL TIME SYSTEMS (1) RESOURCE MANAGEMENT TECHNIQUES (1) results (3) semester 4 (5) semester 5 (1) Semester 6 (5) SERVICE ORIENTED ARCHITECTURE (1) Skill Test (1) software (1) Software Engineering (4) SOFTWARE TESTING (1) Structural Analysis (1) syllabus (34) SYSTEM SOFTWARE (1) system software lab (2) SYSTEMS MODELING AND SIMULATION (1) Tansat (2) Tansat 2011 (1) Tansat 2013 (1) TCP/IP DESIGN AND IMPLEMENTATION (1) TECHNICAL ENGLISH (7) Technology and National Security (1) Theory of Computation (3) Thought for the Day (1) Timetable (4) tips (4) Topic Notes (7) tot (1) TOTAL QUALITY MANAGEMENT (4) tutorial (8) Ubuntu LTS 12.04 (1) Unit Wise Notes (1) University Question Paper (1) UNIX INTERNALS (1) UNIX Lab (21) USER INTERFACE DESIGN (3) VIDEO TUTORIALS (1) Virtual Instrumentation Lab (1) Visual Programming (2) Web Technology (11) WIRELESS NETWORKS (1)

LinkWithin