Strings
A
String represents the sequence of characters the easiest way to represent to a
sequence of characters in java is by using a character array.
Example:
Char
charArray[ ]=new char[4];
CharArray[0]=’J’;
CharArray[1]=’a’;
CharArray[2]=’v’;
CharArray[3]=’a’;
In java strings are class objects
and implemented using two classes, namely, String and StringBuffer. A java
string is an instantiated object of the class String class. A java string is
not a character array and is not NULL terminated. Strings may be declared as
follows:
String Stringname;
Stringname = new
string(“String”);
Example:
String
firstname;
firstname
= new String(“Anil”);
these
two statements may be combined as follows:
String
firstname = new String(“Anil”);
Like
arrays, it is possible to get the length of string using the length
method of the String class.
int
m=firstname.length();
Java
strings can be concatenated using the + operator.
Example;
String
fullName = name1+name2;
String
city = ”New”+”Delhi”;
//Program
to find substring in java
import
java.io.*;
import
java.lang.String;
class
strings
{
public static void main(String
[]args) throws IOException
{
BufferedReader
br=new BufferedReader(new InputStreamReader(System.in));
String fname,sname;
int flag=0;
System.out.println("Enter
the First Name:");
fname=String.valueOf(br.readLine());
System.out.println("Enter
the Second Name:");
sname=String.valueOf(br.readLine());
for(int
i=0;i<fname.length();i++)
{
for(int
j=0;j<sname.length();j++)
{
if(fname.charAt(i)!=(sname.charAt(j)))
continue;
else
flag++;
}
}
if(flag!=0)
System.out.println(sname
+ " is a substring of "+fname);
else
System.out.println(sname
+ " is not a substring of "+fname);
}
}
Output:
D:\
\programs>javac strings.java
D:\
\programs>java strings
Enter
the First Name:
mega
star
Enter
the Second Name:
mega
mega
is a substring of mega star
Commonly
used string methods
Method
Name
|
Task
Performed
|
Converts
string s1 to lowercase
|
|
Converts
string s1 to uppercase
|
|
Replace
all x with y
|
|
Remove
white spaces
|
|
Returns
true is s1=s2
|
|
Returns
true is s1=s2, ignoring the case
|
|
Finds
the length of s1
|
|
Gives
nth character of s1
|
|
Returns
negative if s1<s2, positive if s1>s2, and zero if s1=s2
|
|
Concatenates
s1 and s2
|
|
Gives
substring starting from nth character
|
|
Gives
the position of first occurrence of x in string s1.
|
No comments:
Post a Comment