The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

String and Character
STRING
CREATING STRINGS
STRING LENGTH
CONCAT STRINGS

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by คณพศ ยศพล, 2020-06-22 04:04:51

String and Character

String and Character
STRING
CREATING STRINGS
STRING LENGTH
CONCAT STRINGS

Keywords: STRING,Character

STRING (สายอกั ขระตวั อกั ษร)

• Strings, which are widely used in java programming, are a sequence

of characters. in the java programming language, strings are objects.

• "hello world!" เกิดจาก character ทีม่ าเรียงต่อกนั เป็นสาย
• 'h'+'e'+'l'+'l'+'o'+' '+'w'+'o'+ 'r'+ 'l'+ 'd'+'!’
• สายอกั ขระตวั อกั ษรไม่ใชช่ นดิ ขอ้ มูล (Data Type) แตเ่ ปน็ รูปแบบ Class โดย

String แตล่ ะตวั จะมคี า่ เปน็ Object

CREATING STRINGS

String greeting = "hello.''; หรอื
char [ ] helloarray = {'h', 'e', 'l', 'l', 'o', '.' };
String hellostring = new String(helloarray);
// สร้าง String จาก char []

STRING LENGTH (ความยาวของ STRING)

Methods used to obtain information about an object are known
as accessor methods. One accessor method that you can use with
strings is the length() method, which returns the number of characters
contained in the string object.

String textchat = "I love you.";
int len = textchat.length();

CONCAT STRINGS (การเชื่อมคา)

The string class includes a method for concatting two strings:
String String1 = "my name is ".concat("Marhmello");
String String2 = "Marhmello";

String1.concat(String2);

CONCAT STRINGS (การเช่ือมคา)

Strings are more commonly concatenated with + operator
"Hello" + " world" + "!" results "hello world!"

String1 + String2 ;

CONCAT STRINGS (การเชือ่ มคา)

The + operator is widely used in print statements.
For example :
String string1 = " Golf " ;
System.out.println ("My nickname : " + string1 + "^_^") ;
Output : My nickname : Golf ^_^

ESCAPE SEQUENCES

Constant Meaning
/t
/b Insert a tab in the next at this point
/n Insert a backspace in the next at this point
Insert a newline in the next at this point

ESCAPE SEQUENCES

For example :
String string1 = “ My name is Kalefie ” ;
String string2 = “ My nickname is Kale ” ;
System.out.println ( string1 + “\n” + string2 ) ;
Output : My name is Kalefie

My nickname is Kale

CONVERSION FROM STRING TO NUMBER B and C = 2 (int )

String A = " 7 " ; E and F = 24.537
int B = Integer.parseInt( A ); (double )
int C = Integer.valueOf( A );
String D = " 24.537 " ;
double E = Double.parseDouble( D );
double F = Double.valueOf( D );

CONVERT NUMBER TO STRING

int b = 3 ; String d = String.valueOf(b);

double c = 4.2 ; String e = String.valueOf(c);

GETTING CHARACTERS

String anotherPalindrome = "Niagara. O roar again!";
char Achar = anotherPalindrome.charAt(9);
การดงึ char ออกมาจาก string โดยใช้ index
Achar = 'O' ;

SUBSTRINGS BY INDEX

Starting index :
substring(int beginIndex , int endIndex)

Starting index and end index :
substring(int beginIndex)

SUBSTRINGS BY INDEX

Exam :
String str = new String ("Lets Learn Java");
System.out.println("substring(1):"+ str.substring(1));
System.out.println("substring(1,3):"+ str.substring(1,3));

Output :

SUBSTRINGS BY INDEX

String anotherPalindrome = "Niagara. O roar again!";

String str =anotherPalindrome.substring(11, 15);

SPLIT() – แยก STRING ด้วย PATTERN

String [ ] split (String regex) เอาไวแ้ ยก String ออกเป็นส่วนๆ แล้วเก็บไว้ใน array
String a = "CPE:IT:RAE:IE:AME: [ET]@PIM";
String [ ] b = a.split(":");
System.out.println(Arrays.toString(b));
Output :
[CPE, IT, RAE, IE, AME, [ET]@PIM]

TRIM() ตัดชอ่ งว่างด้านหนา้ และหลังท้งิ

String a = " Java is easy ";
String b = a.trim();
System.out.println(b);

Output :
"Java is easy"

TOLOWERCASE() AND TOUPPERCASE()

แปลงตวั อักษรใหเ้ ปน็ ตวั พิมพ์เล็กหรอื ตวั พมิ พ์ใหญ่ทง้ั หมด

String a = "JAVA IS EASY"; String a = "java is easy";
String b = a.toLowerCase(); String b = a.toUpperCase();
System.out.println(b); System.out.println(b);
Output : Output :
"java is easy" "JAVA IS EASY"

SEARCH IN STRING (indexOf)

String str = "Hi welcome to Java Class";
// returns index position for the given to value
int index1 = str.indexOf('w');
// returns index position for the given to value from index
// It returns -1 if substring does not found
int index2 = str.indexOf('w',3);
System.out.println("Index of the letter w "+index1 + ":" + index2);
Output :
Index of the letter w 3 : 3

SEARCH IN STRING (lastIndexof)

String str = “www.google.com";
int index = str.lastIndexOf('w');
System.out.println("Index of the letter w :: "+index);

Output :
Index of the letter w :: 2

lastIndexOf vs indexOf String a = "www.youtube.com" ;
String b = a.lastIndexOf('o');
String a = "www.youtube.com" ; System.out.println(b);
String b = a.indexOf('o'); Output :
System.out.println(b); 13
Output :
5 Last character found

First character found

CONTAINS ()

// ให้คา่ true เม่อื argument นั้นไดฝ้ ังอย่ใู น String น้นั
// false เมื่อไม่ไดอ้ ยู่ใน String นัน้
String str_Sample = "This is a String contains Example";
System.out.println(str_Sample.contains("Example"));
System.out.println(str_Sample.contains("example"));
Output :
true
false

REPLACE

Method replace(oldChar, newChar)
replace(oldString, newString)

Return String,char
Property
Sample ใช้เพ่ือแทนคา่ ข้อความหรือตวั อักษร

display public class learnjava {
public static void main(String [] args) {
String a = "jav";
System.out.print(a.replace("v", "va is easy"));
}

}
java is easy

REPLACEALL

Method replaceAll(String regex, String)
Return
Property String

Sample ใชเ้ พ่ือแทนคา่ ขอ้ ความทกุ ตวั ท่เี ลอื ก
public class learnjava {
display
public static void main(String [] args) {
String a = " Love you i i ";
System.out.print(a.replaceAll("i", "ei"));

}
}
Love you ei ei

REPLACEFIRST

Method replaceFirst(String regex, String)
Return
Property String

Sample ใชเ้ พื่อแทนขอ้ ความเฉพาะตวั แรกที่เลอื ก
public class learnjava {
display
public static void main(String [] args) {
String a = " Love you i i ";
System.out.print(a.replaceFirst ("i", "ei"));

}
}
Love you ei i

IMMUTABLE OF A STRING

Let's run this code !

String d = "I love yoo";
d.replace(("yoo"), ("you"));
System.out.println(d); // Output display ?

COMPARING STRINGS

 boolean endsWith(String suffix)
 boolean startsWith(String prefix)
 int compareTo(String anotherString)
 int compareToIgnoreCase(String str)
 boolean equals(Object anObject)
 boolean equalsIgnoreCase(String anotherString)

STARTSWITH

Method startsWith(String)
Return startsWith(String, index)
Property boolean
ใชต้ รวจสอบส่วนหน้าของขอ้ ความ
Sample ใช้กาหนดตาแหนง่ สว่ นหน้าของขอ้ ความและตรวจสอบส่วนหนา้ ของขอ้ ความ

display public class learnjava {
public static void main(String[] args) {
String a = "java i i good";
System.out.print(a. startsWith("va", 2));
}}

true

ENDSWITH

Method endsWith(String)
Return
Property boolean

Sample ใชต้ รวจสอบสว่ นท้ายของขอ้ ความ
public class learnjava {
display
public static void main(String[] args) {
String a = "Java";
System.out.print("Show : " + a.endsWith("va"));

}
}
true

COMPARE OF STRING Meaning

Method Compare numeric values in strings.

compareTo(); Compare numeric values in strings.
compareToIgnoreCase(); Ignore for the font size.

equals(); Check the texts are equal or not.
equalsIgnoreCase();
Check the texts are equal or not.
Ignore for the font size.

COMPARE OF STRING -32
false
String a = "Pim";
String b = "pim"; 0
System.out.println(a.compareTo(b)); false
System.out.println(a==b); true
System.out.println(a.compareToIgnoreCase(b));
System.out.println(a.equals(b));
System.out.println(a.equalsIgnoreCase(b));

POINTERS IN HEAP

String s1 = "Hello"; String s4 = new String("Hello"); s1 == s1; // true, same pointer
String s2 = "Hello"; String s5 = new String("Hello"); s1 == s2; // true, s1 and s1 share storage in
String s3 = s1;
common pool
s1 == s3; // true, s3 is assigned same

pointer as s1
s1.equals(s3); // true, same contents
s1 == s4; // false, different pointers
s1.equals(s4); // true, same contents
s4 == s5; // false, different pointers in heap
s4.equals(s5); // true, same contents

INTERNING OF STRING IN JAVA

String s1 = new String("PIM"); // S1 refers to Object in the Heap Area

String s2 = s1.intern(); // S2 refers to Object in Common Pool Area

// Comparing memory locations Heap Area Common Pool
System.out.println(s1 == s2);
// Comparing only values S1 S2,S3

PIM PIM

System.out.println(s1.equals(s2));

String s3 = “PIM"; // S3 refers to Object in Common Pool Area

System.out.println(s2 == s3); // Comparing memory locations

AUTOBOXING AND UNBOXING

Autoboxing:
Converting a primitive value into an object

of the corresponding wrapper class is called
autoboxing

Unboxing:
Converting an object of a wrapper type to

its corresponding primitive value is called
unboxing

AUTOBOXING

The compiler automatically handles the conversion when a primitive value is:
1. Passed as an argument to a function which is expecting a wrapper class object.
2. assigned to a variable of the type of wrapper class.

List<Integer> list = new ArrayList<>(); //autoboxing by assigning an char to Character object
for(int i = 0; i< 10; i++){ char c = 'a';
Character ch = c;
//autoboxing by passing as an argument System.out.println(ch);
//int values is converted to Integer
//by compiler during compilation
list.add(i); }
System.out.println(list);

UNBOXING

The compiler automatically handles the conversion when a wrapper object is:
1. Passed as an argument to a function which is expecting a primitive data type variable.
2. Assigned to a variable of the type of primitive data type variable.

//unboxing by passing as an argument //unboxing by assigning an Integer object to int variable
//Integer object is converted to int Integer integer = new Integer(-20);
//by compiler during compilation int j = integer;
System.out.println(j);
Integer integer = new Integer(-10);
int i = abs(integer);
System.out.println(i);

OTHER INTERESTING METHODS

 isEmpty()
 subSequence(index, index)
 copyValueOf()

isEmpty()

Method isEmpty()
Return
Property boolean
Sample
ใชเ้ พ่อื ตรวจสอบวา่ String วา่ งหรอื ไม่
display
public class learnjava {
public static void main(String[] args) {
String a = "Java";
System.out.print("Show : " + a.isEmpty());
}

}
Show : false

subSequence()

Method subSequence(index, index)
Return
Property String
Sample
ใชเ้ พ่อื ตดั ข้อความในตาแหน่งทตี่ ้องการ
display
public class learnjava {
public static void main(String[] args) {
String a = "Java";
System.out.print(a.subSequence(2, 4));
}

}
va

copyValueOf()
copyValueOf(char[])
Method copyValueOf(char[], index, count)

Return String

Property ใช้เพ่ือนาขอ้ มูลอักขระจากอาเรย์มารวมเปน็ คา

Sample public class learnjava {

public static void main(String[] args) {

char[] a = {'J','a','v','a'};

String b = String.copyValueOf(a);

String c = String.copyValueOf(a, 1, 2);

System.out.println(b);

System.out.print(c); } }

display Java

va

CHARACTER CLASS

CHARACTER METHOD

 Character.isDigit()
 Character.isLetter()
 Character.isLowerCase()
 Character.isUpperCase()
 Character.toLowerCase()
 Character.toUpperCase()
 Other

Character.isDigit()

Method isDigit(char ch)
Return
Property boolean

Sample This method Returns true if passed character is a number.
public class Test {
display
public static void main(String args[]) {
System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('5'));
}
}
false
true

Character.isLetter()

Method isLetter(char ch)
Return
Property boolean

Sample This method Returns true if passed character is a letter.
public class Test {
display
public static void main(String args[]) {
System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('5'));
}
}
true
false

Character.isLowerCase()

Method isLowerCase()
Return
Property boolean

Sample This method Returns true if passed character is an lowercase.
public class Test {
display
public static void main(String args[]) {
System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('C'));
}
}
true
false

Character.isUpperCase()

Method isUpperCase()
Return
Property boolean

Sample This method Returns true if passed character is an uppercase.
public class Test {
display
public static void main(String args[]) {
System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('C'));
}
}
false
true

Character.toLowerCase()

Method toLowerCase()
Return
Property char

Sample This method Returns character is an lowercase.
public class Test {
display
public static void main(String args[]) {
System.out.println(Character.toLowerCase('c'));
System.out.println(Character.toLowerCase('C'));
}
}
‘c’
‘c’

Character.toUpperCase()

Method toUpperCase()
Return
Property char

Sample This method Returns character is an uppercase.
public class Test {
display
public static void main(String args[]) {
System.out.println(Character.toLowerCase('c'));
System.out.println(Character.toLowerCase('C'));
}
}
‘C’
‘C’

toString(char ch)

Method toString(char ch)
Return
Property String

Sample This method Returns String object.
public class Test{
display
public static void main(String args[]){
System.out.println(Character.toString('c'));
System.out.println(Character.toString('C'));
}
}
“c”
“C”

isWhitespace(char ch)

Method isWhitespace(char ch)

Return boolean
Property
Sample This method Returns true if there is free space.

display public class Test{
public static void main(String args[]){
System.out.println(Character.isWhitespace('c'));
System.out.println(Character.isWhitespace(' '));
System.out.println(Character.isWhitespace('\n'));
System.out.println(Character.isWhitespace('\t')); } }

false
true
true
true


Click to View FlipBook Version