More on iterations using String and Char More on iterations using
Outlines Strings String variables Concatenation length() charAt() Iteration examples using length() and CharAt()
Characters and Strings A String is a series of chars. We can treat the series as one unit There are methods in the Java API we can use on strings
String variables String variables are unlike other variables we have used in this class. String variables are called reference variables because they hold a reference to where the string is stored in memory. Example: String s = "A string of characters";
String concatenation Two Strings together using the + operator to form a new string. This is called concatenation. The following statements: String s1 = “Hello "; String s2 = “Lahcen "; String s3 = s1 + s2; assigns the String “Hello Lahcen" to the variable s3.
String's charAt() method String also has a method called charAt() which can be used to return any single character in a String. Note: The first letter in a string is considered to be in position zero. For example, if we have: String s = "Hello"; s.charAt (0) will return 'H' s.charAt (4) will return 'o' s.charAt (5) will return StringIndexOutOfBoundsException
String's length() method All Strings know their own length. To find out the length of a string, we use String's length() method. For example: String s = "Hello"; int length = s.length(); Will place the value 5 in variable length.
Example Using while of for loops to write a program CountChartA.java. The program asks the user to enter a string and prints the number character ‘a’ in the string.
Answer with for loop import java.util.*; public class CountchartA { public static void main(String[] args) Scanner in = new Scanner(System.in); String s = in.nextLine(); int count = 0; for (int i=0; i < s.length(); i++) if (s.charAt(i) == 'a') count++; } if (count>1) {System.out.println("there are " + count + " charater 'a'");} else {System.out.println("there is " + count +" charter 'a'");}
Answer with while loop import java.util.*; public class CountchartA { public static void main(String[] args) Scanner in = new Scanner(System.in); String s = in.nextLine(); int count = 0; int I =0; while(i < s.length();) if (s.charAt(i) == 'a') count++; } i++; if (count>1) {System.out.println("there are " + count + " charater 'a'");} else {System.out.println("there is " + count +" charter 'a'");}
Example Using while of for loops to write a program StringReverse.java. The program asks the user to enter a string prints the string in reverse order i.e. if the the use enters “Hello”. the programs prints “olleH”.
Answer with while loop import java.util.*; public class StringReverse { public static void main(String[] args) Scanner in = new Scanner(System.in); String s = in.nextLine(); String rs = ""; for (int i=0; i < s.length(); i++) rs = s.charAt(i)+ rs; } System.out.println(rs);