Posts

Showing posts from September, 2014

Conversion between Strings and Arrays

Strings are not arrays, but a string can be converted into an array, and vice versa. To convert a string to an array of characters, use the toCharArray method. For example, the following statement converts the string "Java" to an array. char[] chars="Welcome to Java".toCharArray(); So chars[0] is 'J', chars[1] is 'a', chars[2] is 'v', and chars[3] is 'a' and so on... You can also use the getChars(int srcBegin, int srcEnd, char[] dst, int dst- Begin) method to copy a substring of the string from index srcBegin to index srcEnd-1 into a character array dst starting from index dstBegin. For example, the following code copies a substring "to java" in "Welcome to java" from index 7 to str.lenth()-1 into the character array dst starting form index 0. import java.lang.String; class stringtochars{                                 public static void main(String[] arg){                                 char[] chars=

Finding a Character or a Substring

The String class provides several overloaded indexOf and lastIndexOf methods to find a character or a substring in a string. Method syntax Return type Description +indexOf(ch:char) int Returns the index of the first occurrence of ch in the string. Returns-1 if not matched. +indexOf(ch:char,formIndex:int) int Return the index of the first occurrence of ch after fromIndex in the string. Return -1 in not matched. +indexOf(str:string) int Returns the index of the first occurrence of string s in this string. Returns-1 if not matched. +indexOf(str:string,fromIndex:int) int Returns the index of the first occurrence of string s in this string after fromIndex. Returns -1 if not matched. +lastIndexOf(ch:char) int Returns the index of the last occurrence of ch in the string. Returns-1 if not matched.  +lastIndexOf(ch:char,fromIndex:int) int Returns the index of the last occurrence of ch before fromIndex in this string. Returns -1 if not matched.  +lastInde

+split(delimeiter:String);

Return type String[] (Array of string). Returns an array of strings consisting of the substrings split by the delimiter. import  java.lang.String; class split{                      public static void main(String[] arg){                       String[] str="Welcome_to_Java".split("_",0);                      for(int i=0;i<str.length;i++)                             System.out.println(str[i]);                                           } } Output:   Welcome               to              Java

+replaceAll(old string:string,newstring:string);

Return type String. Returns a new string that replaces all matching substrings in this string with the new substring. import  java.lang.String; class replaceAll{                      public static void main(String[] arg){                       System.out.println("Welcome : "+"Welcome".replaceAll("e","EL"));                      } } Output:   Welcome : WELlcomEL

+replaceFirst(OldString:string,newString:string);

Return type String Returns a new string that replaces the first matching substring in this string with the new substring. import java.lang.String; class replacefirst{                             public static void main(String[] args){                             System.out.println("Welcome : ","Welcome".replaceFirst("e","E"));                             } } Output :    Welcome : WElcome

+replace(oldchar,newchar);

Return type String Returns a new string that replaces all matching characters in this string with the new character. import  java.lang.String; class replace{                      public static void main(String[] arg){                       System.out.println("Welcome : "+"Welcome".replace('e','E'));                      } } Output:   Welcome : WElcomE

+trim()

Return type String Returns a new string with blank characters trimmed on both sides. import java.lang.String; class trim{                  public static void main(String[] arg){                  System.out.pringln("    Welcome    :"+"     Welcome     ".trim());                  } } Output:       Welcome     :Welcome

+toUpperCase()

Return type String Returns a new string with all characters converted to uppercase. import java.lang.String; class touppercase{                                public static void main(String[] args){                                System.out.println("WelcoMe : "+"WelcoMe".toUpperCase());                                } } Output:   WelcoMe : WELCOME

+toLowerCase

Return type String Returns a new string with all characters converted to lowercase.  import java.lang.String; class tolowercase{                               public static void main(String[] args){                               System.out.println("WELCOME : "+"WELCOME".toLowerCase());                               } } Output : WELCOME : welcome

Converting, Replacing and Splitting Strings

The String class provides the methods for converting, replacing and splitting strings as given in table. java.lang.String Method syntax Return type Description +toLowerCase() String Returns a new string with all characters converted to lowercase +toUpperCase() String Returns a new string with all characters converted to uppercase +trim() String Returns a new string with blank characters trimmed on both sides +replace(oldChar:char, newChar:char) String Returns a new string that replaces all matching characters in this string with the new character +replaceFirst(oldString:String, newString:String) String Returns a new string that replaces the first matching substring in this string with the new substring +replaceAll(oldString:String, newString:String) String Returns a new string that replaces all matching substrings in this string with the new substring

Obtaining Substrings

You can obtain a single character from a string using the charAt() method. You can also obtain a substirng from a string using the substring method in the String class. java.lang.String +substring(beginIndex: int);                            return type String +subString(beginIndex: int, endIndex: int);     return type Sting +substring(beginIndex: int) this string's substring that begins with the character at the specified beginIndex and extends to the end of the string.  Click here for example . + substring(beginIndex: int, endIndex: int) this string's substring that begins with the character at the specified beginIndex and extends to specified endIndex of the string. Click here for example .  Note But it will not include endIndex character in substring.

+substring(beginIndex: int, endIndex: int); return type String

Image
import java.lang.String; class subStringstartend{                     public static void main(String[] arg){                            String str1="Welcome to Java";                           String str2=str1.substring(3,11);                                                     System.out.println("str1: "+str1);                           System.out.println("str2=str1.substring(3,11): "+str2);                          }                      } Output:   str1: Welcome to Java               str2=str1.substring(3,11): come to Note: If beginIndex is endIndex , substring(beginIndex, endIndex) return an empty string with length 0. If beginIndex > endIndex, it would be run time error. import java.lang.String; class subStringstartend{                     public static void main(String[] arg){                            String str1="Welcome to Java";                           String str2=str1.substring(11,2);                      

+substring(beginIndex: int) return type string

Image
import java.lang.String; class subStringstart{                     public static void main(String[] arg){                            String str1="Welcome to Java";                           String str2=str1.substring(3);                                                     System.out.println("str1: "+str1);                           System.out.println("str2=str1.substring(3): "+str2);                          }                      } OutPut  :   str1: Welcome to Java                  str2=str1.substring(3): come to Java

+concat(str: string) return type string

import java.lang.String; class concat{                     public static void main(String[] arg){                            String str1="Welcome";                           String str2=" to Java";                           String str3=str1.concat(str2);                           System.out.println("str1.concat(str2): "+str3);                          }                      } Output:   str1.concat(str2): Welcome to Java String str3=str1.concat(str2); Since string concatenation is heavily used in programming, java provides a convenient way to accomplish it. You can use the plus ( + ) sign to concatenate two or more strings. So the above statement is equivalent to String str3=str1+str2; The following code combines the strings str1, str2, "and" and "Smartprogrammeron.blogspot.in" into one string: String str3=str1+str2+"and"+"Smartprogrammeron.blogspot.in"; Recall that the + sign can also concatenate

+charAt(index: int) return type char

Image
The str.CharAt(index) method can be used to retrieve a specific character in a string str, where the index of between 0 and str.length()-1 . import java.lang.String; class charAt{                     public static void main(String[] arg){                            String str="Welcome to Java";                           System.out.println("str.charAt(0): "+str.charAt(0));                          }                      } Output:   str.charAt(0): W Here:  str.charAt(0) returns the character W, as show in output and in fig given below. Attempting to access characters in a string str out of bounds is common programming error. To avoid it, make sure that you do not use an index beyond str.length()-1 . For exmaple:- import java.lang.String; class charAt{                     public static void main(String[] arg){                            String str="Welcome to Java";                           System.out.println("str.charAt(0): &

+length(): return type int

You can get length of a string by invoking its length() method. import java.lang.String; class length{                     public static void main(String[] arg){                            String str="Welcome to Java";                           System.out.println("Length: "+str.length());                          }                      } Output:   Length: 15     Note that length is a method in the String class but is a property in an array object. Do you have to use str.length() to get the number of characters in string str and a.length to get the number of elements in array a.

String Length, Characters, and Combining Strings

The String class provides the methods for obtaining length, retrieving individual characters, and concatenating strings. java.lang.String +length();                   return type int +charAt(index : int);   return type char +concat(str1 : String);    return type String The String class contains the methods for getting string length, individual characters and combing strings. You can get the length of a string by invoking its length() method. Click here for example . You can retrieve a specific character from a string by using charAt(index :  int) method. Click here for example. Note : -   A string value is represented using a private array variable internally. The array cannot be accessed outside of the String class. The String class provides many public methods, such as length() and charAt(index), to retrieve the array information. This is a good example of encapsulation: the data field of the class is hidden from the user through the private modifier and

Like Us on facebook

Image

WAP for to draw beatsaudio logo using circles and line(OpenGL)

Image
#include<GL/glu.h> #include<GL/glut.h> #include<GL/gl.h> using namespace std; void draw(int i) {      if(i!=20)      glClear(GL_COLOR_BUFFER_BIT);      int add=10; if(i==20)      add=15;      for(int r=i;r<=i+add;r++)      {      glPointSize(2);      glColor3f(1.0,0.0,0.0);      glBegin(GL_POINTS);              int yk=r;              int xk=0;              int p,p0=1-r;              p=p0;              int x=0,y=r;              glVertex2i(xk,yk);              glVertex2i(-xk,-yk);              glVertex2i(yk,-xk);              glVertex2i(-yk,xk);              while(x<=y)              {                      if(p<0)                      {                      x+=1;                      glVertex2i(x,y);                      glVertex2i(y,x);                      glVertex2i(-x,-y);                      glVertex2i(-y,-x);                      glVertex2i(x,-y);                      glVertex2i(-y,x);                      glVertex2

Bresnham's Line Algorthim

Image
#include<GL/glu.h> #include<GL/glut.h> #include<GL/gl.h> using namespace std; void draw(int x0, int y0,int  x1,int y1) {      glClear(GL_COLOR_BUFFER_BIT);       glPointSize(2);      glColor3f(1.0,0.0,0.0);      glBegin(GL_POINTS);      int dx=x1-x0;      int dy=y1-y0;      int x=x0,y=y0;      int p,p0=2*dy-dx;      p=p0;      glPointSize(2);      glVertex2i(x0,y0);      while(x!=x1&&y!=y1)      {             if(p<0)             {                 x=x+1;                 glVertex2i(x,y);                 p=p+2*dy;             }             else             {                 x+=1;                 y+=1;                 glVertex2i(x,y);                 p=p+2*dy-2*dx;             }      }      glEnd();      glFlush(); } void init() {    glMatrixMode(GL_PROJECTION);    glLoadIdentity();    gluOrtho2D(-50, 50, -50, 50); } void display() {      draw(20,10,30,18); } int main(int argc,char **argv) {      glutInit(&a

WAP for DDA

Image
#include<GL/glut.h> #include<stdio.h> #include<stdlib.h> void plot(int xa,int ya,int xb, int yb) {         int dx=xb-xa;         int dy=yb-ya;         int steps,k;         float xIncrement,yIncrement;         float x=xa,y=ya;         glPointSize(5);         glClear (GL_COLOR_BUFFER_BIT);         glColor3f (1.0, 1.0, 0.0);           if(abs(dx)>abs(dy))               steps=abs(dx);         else              steps=abs(dy);         xIncrement=dx/(float)steps;         yIncrement=dy/(float)steps;         glBegin(GL_POINTS);         glVertex2i(x,y);         for(k=0;k<steps;k++)        {                 x+=xIncrement;                 y+=yIncrement;                 glVertex2i(x,y);         }         glEnd();         glFlush(); } void init() {         glMatrixMode(GL_PROJECTION);         glLoadIdentity();         gluOrtho2D(-10,10,-10,10); } void disp() {          plot(0,0,6,4);     // End points of line(x0,y0,x1,y1) } int mai

String Comparisons

The String class provides the methods for comparing strings, as given below:-                       Method                                                            Defination str2.equals(s1: String): boolean                        Returns true if this string is equal to string s1. str2.equalsIgnoreCase(s1: String): boolean      Returns true if this string is equal to string s1 case                                                                                   insensitive. str2.compareTo(s1: String): int                        Returns an integer greater than 0, equal to 0, or less                                                                                 than 0 to indicate whether this string is greater than,                                                                                 equal to, or less than s1. str2.compareToIgnoreCase(s1: String): int      Same as compareTo except that the comparison is case                                                      

str2.endsWith(suffix: String): boolean

Image
class endswith { public static void main(String[] arg) { String str1 = "Welcome to Smartprogrammeron.blogspot.in"; System.out.println("str1.endsWith(\"in\") is " + str1.endsWith("in"));        System.out.println("str1.endsWith(\"iN\") is " + str1.endsWith("iN")); } } To check is strings ends with given string or not. It case sensitive.

str2.startsWith(prefix: String): boolean

Image
class startwith { public static void main(String[] arg) { String str1 = "Welcome to Smartprogrammeron.blogspot.in"; System.out.println("str1.startsWith(\"Wel\") is " + str1.startsWith("Wel"));        System.out.println("str1.startsWith(\"wel\") is " + str1.startsWith("wel")); } } To check prefix. Is string starting with given string or not. It is case sensitive.

str2.regionMatches(ignoreCase: boolean, index: int, str1: String, str1Index: int, len: int): boolean

Image
class regionignorecase { public static void main(String[] arg) { String str1 = "Welcome to Smartprogrammeron.blogspot.in"; String str2 = new String("Welcome to SmartProgrammerOn.blogspot.in"); System.out.println("str1.regionMatchescase(ignoreCase:true or fasle,offset of str1=10,str2,offset of str2=10,length=25) is " + str1.regionMatches(true,\10,str2,10,25));        System.out.println("str1.regionMatchescase(ignoreCase:true or fasle,offset of str1=0,str2,offset of str2=0,length=10) is " + str1.regionMatches(true,0,str2,0,10)); } } for true of ignoreCase it will ignore upper case and lower case but for false it will work case sensitive.

str2.regionMatches(index: int, s1: String,s1Index: int, len: int): boolean

Image
class region { public static void main(String[] arg) { String str1 = "Welcome to Smartprogrammeron.blogspot.in"; String str2 = new String("Welcome to SmartProgrammerOn.blogspot.in"); System.out.println("str1.regionMatches(offset of str1=10,str2,offset of str2=10,length=25) is " + str1.regionMatches(10,str2,10,25));        System.out.println("str1.regionMatches(offset of str1=0,str2,offset of str2=0,length=10) is " + str1.regionMatches(0,str2,0,10)); } } It will match on given region of two strings.

str2.compareToIgnoreCase(s1: String): int

Image
class compareignore { public static void main(String[] arg) { String str1 = "Welcome to Smartprogrammeron.blogspot.in"; String str2 = new String("Welcome to SmartProgrammerOn.blogspot.in"); System.out.println("str1.compareToIgnore(str2) is " + str1.compareToIgnoreCase(str2)); } } str2.compareToIgnoreCase(s1: String): int   case insensitive.

str2.compareTo(s1: String): int

Image
class compare { public static void main(String[] arg) { String str1 = "Welcome to Smartprogrammeron.blogspot.in"; String str2 = new String("Welcome to SmartProgrammerOn.blogspot.in"); System.out.println("str1.compareTo(str2) is " + str1.compareTo(str2)); } } The compareTo method can also be used to compare two strings.  For example, consider the following code:    s1.compareTo(s2) The method returns the value 0 if s1 is equal to s2, a value less than 0 if s1 is lexicographi- cally (i.e., in terms of Unicode ordering) less than s2, and a value greater than 0 if s1 is lexi- cographically greater than s2. The actual value returned from the compareTo method depends on the offset of the first two distinct characters in s1 and s2 from left to right. For example, suppose s1 is "abc" and s2 is "abg", and s1.compareTo(s2) returns -4. The first two characters (a vs. a) from s1 and s2 are compared. Because they are eq

str2.equalsIgnoreCase(s1: String): boolean

Image
class equalsignor { public static void main(String[] arg) { String str1 = "Welcome to Smartprogrammeron.blogspot.in"; String str2 = new String("Welcome to SmartProgrammerOn.blogspot.in"); System.out.println("str1.equals(str2) is " + str1.equals(str2)); System.out.println("str1.equalsIgnoreCase(str2) is " + str1.equalsIgnoreCase(str2)); } } str2.equalsIgnoreCase(s1: String): boolean  ;- it ignore upper and lower case but str1.equals(str2:String):boolean will not ignore upper and lower case.

str2.equals(s1: String): boolean

Image
class equals { public static void main(String[] arg) { String str1 = "Welcome to Smartprogrammeron.blogspot.in"; String str2 = new String("Welcome to Smartprogrammeron.blogspot.in"); System.out.println("str1.equals(str2) is " + str1.equals(str2)); System.out.print("str1 == str2 is "); System.out.print(str1==str2); } } However, the == operator checks only whether str1 and str2 refer to the same object; it does not tell you whether they have the same contents. Therefore, you cannot use the == operator to find out whether two string variables have the same contents. Instead, you should use the equals method.

Immutable String and Interned Strings

Image
A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; The answer is no. The first statement creates a String object with the content “Java” and assigns its reference to s. The second statement creates a new String object with the con- tent “HTML” and assigns its reference to s. The first String object still exists after the assignment, but it can no longer be accessed, because variable s now points to the new object, as shown in Figure Since strings are immutable and are ubiquitous in programming, the JVM uses a unique instance for string literals with the same character sequence in order to improve efficiency and save memory. Such an instance is called interned. For example, the following statements: class immutable { public static void main(String[] arg) { String str1 = "Welcome to Smartprogrammeron.blogspot.in"; String str2 = new String("

Constructing a String

Image
You can create a string object from a string value of from an array of characters. To create a string from a string literal, us a syntax like this one: String str1=new String("Hello"); Hello is string literal a sequence of characters enclosed inside double quotes.  Java treats a string literal as a String object. So the Statement is valid:-  String str1="Hello"; You can also create a string from an array of characters. For example, the following statements create the string "Hello". char[] charary={'H,'e','l','l','o'}; String message = new String(charary); Note:-    A String variable holds a reference to a String object that stores a string value. Strictly speaking, the term String variable. String object and String value are different, but most of time the distinctions between them can be ignored. For simplicity the term string will often be used to refer to String variable, String object and St

The String Class

public final class String extends Object implements Serializable, Comparable<String>, CharSequence The  String  class represents character strings. All string literals in Java programs, such as  "abc" , are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: String str = "abc"; is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data); Here are some more examples of how strings can be used: System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2,3); String d = cde.substring(1, 2); The class  String  includes methods for examining individual characters of the sequence, for comparing strin

Introduction

Often you encounter problems that involve string processing and file input and out. Suppose you need to write a program that replaces all occurrences of a word in a file with a new word. How do you solve this problem? Smartprogrammeron.blogspot.in introduces strings which will enable you to solve this type of problem.

To change all lower case later to upper case latter

Image
import java.lang.Character; class lowerupper { public static void main(String[] arg) { String str=new String("HeLLo tHis iS a JaVa prOgrAM"); char[] str1=str.toCharArray(); Character ch = str.charAt(0); for(int i=0;i<str.length();i++) { ch=str.charAt(i); if(ch.isUpperCase(ch)) { str1[i]=ch.toLowerCase(ch); } else { str1[i]=ch.toUpperCase(ch); } } String str2=new String(str1); System.out.println(str2); } }

Change last character of each latter in Upper Case

Image
import java.lang.Character; class lastuper { public static void main(String[] arg) { String str=new String("hello this is a java program"); char[] str1=str.toCharArray(); Character ch = str.charAt((str.length()-1)); str1[(str.length()-1)]=ch.toUpperCase(ch); for(int i=0;i<str.length();i++) { if(str.charAt(i)==' '&&(i-1)!=0) { ch=str.charAt(i-1); str1[i-1]=ch.toUpperCase(ch); } } String str2=new String(str1); System.out.println(str2); } }

Change first character of each latter in UPPER CASE

Image
import java.lang.Character; class upercase { public static void main(String[] arg) { String str=new String("hello this is a java program   "); char[] str1=str.toCharArray(); Character ch = str.charAt(0); str1[0]=ch.toUpperCase(ch); for(int i=0;i<str.length();i++) { if(str.charAt(i)==' '&&(i+1)!=str.length()) { ch=str.charAt(i+1); str1[i+1]=ch.toUpperCase(ch); } } String str2=new String(str1); System.out.println(str2); } }