Downloaded from: justpaste.
it/mqt25
224UP
import [Link];
import [Link];
import [Link];
public class StringMethods {
public static void main(String[] args) {
String welcomeString = "Welcome to Upgrad Campus";
int len = [Link](); // Get length of string ([Link]() gives 24)
[Link](len); // Prints 24
[Link]("\n\nThe isEmpty(), isBlank() method :");
[Link]([Link]()); // Returns false (because length is NOT 0)
[Link](" ".isEmpty()); // Returns false because length is NOT 0
[Link](" \t ".isBlank()); // Returns true because String only has WhiteSpace
characters
[Link]("\n\nThe toUpperCase(), toLowerCase() method :");
[Link]([Link]()); // Prints "WELCOME TO UPGRAD
CAMPUS"
[Link]([Link]()); // Prints "welcome to upgrad campus"
[Link]("\n\nThe [Link]() method :");
char[] characters = {'H','e','l','l','o'};
String helloFromCharArray = [Link](characters);
[Link](helloFromCharArray); // Prints "Hello" (the string formed from char
array)
[Link]("\n\nThe charAt() method :");
[Link]([Link](0)); // Prints 'W'
[Link]([Link](23)); // Prints 's'
[Link]([Link](len-1)); // Prints 's'
char thirdCharacter = [Link](2);
[Link](thirdCharacter); // Prints 'l'
int firstCharCodePoint = [Link](0); // Getting unicode codepoint of first
character
[Link]("\n\nThe indexOf() method: ");
[Link]([Link](25)); // Prints -1
[Link]([Link](87)); // Prints 0 (87 is UNICODE for 'W' which
occurs at index 0)
[Link]([Link](87,3)); // Prints -1 ('W' doesn't occur at or after
index 3)
// You can have negative values or values greater than equal to length of the string for
fromIndex
// It doesn't throw exception for invalid fromIndex values
[Link]([Link]('a',3,10)); // Prints -1 ('a' doesn't occur at index
0-9)
[Link]([Link]('a',3,17)); // Prints 15 ('a' occurs at index 15)
String stringWithSupplementaryCharacter = "something here, \uD861\uDC02 abc";
[Link]([Link](164866)); // Prints 16
// 164866 is outside of the BMP characters (Unicode code points) and is integer
representation
// of surrogate pair (\uD861\uDC02) [which is a Unicode supplementary character]
// This code-point first occurs at index 16 [and takes index 16 and 17]
[Link]([Link]("come to Upgrad"));
[Link]([Link]("come to Upgrad",10)); // Prints -1
// Given string doesn't occur on or after 10
[Link]([Link]("come to Upgrad",1,15)); // Prints -1
// (given string doesn't occur in [0-14]
[Link]("\n\nThe lastIndexOf() method: ");
[Link]([Link]('a')); // Prints 19 (Last index of 'a' is 19)
[Link]([Link]('x')); // Prints -1
[Link]([Link]('a',19)); // Prints 19
[Link]([Link]('a',18)); // Prints 15 (Last index of 'a' from 0
to 18)
// (searches backwards)
// Following are also available:
// lastIndexOf(String)
// lastIndexOf(String,int beginIndex)
// lastIndexOf(String,int beginIndex,int endIndex)
[Link]("\n\nThe subString() method :");
[Link]([Link](4)); // Prints "ome to Upgrad Campus" (from
index 4)
[Link]([Link](11,17)); // Prints "Upgrad" (index 11 to 16)
[Link]("\n\nThe concat() method :");
[Link]([Link](" and LPU")); // Prints "Welcome to Upgrad
Campus and LPU"
// Note: Concat returns a new String (doesn't modify existing String)
// Thus, welcomeString is still same. (welcomeString = "Welcome to Upgrad
Campus")
[Link]("\n\nThe + operator :"); // concatenation using + operator
[Link](welcomeString +" and LPU"); // Prints "Welcome to Upgrad Campus
and LPU"
[Link]("\n\nThe replace() method :");
[Link]([Link]('a','#')); // Prints "Welcome to Upgr#d C#mpus"
// replace() replaces all occurrences of oldChar with newChar and returns NEW string
// If the character doesn't occur, it returns reference to the original string (doesn't create
new one)
[Link]("\n\nThe replaceFirst(regex,replacement) method :");
[Link]([Link]("Welc","C")); // Prints "Come to Upgrad
Campus"
[Link]([Link]("u|a","###")); // Prints "Welcome to
Upgr###d Campus"
[Link]([Link]("o|u|a","###")); // Prints "Welc###me to
Upgrad Campus"
String maxValueOfIntString = "Maximum value of INT_MAX is maximum value that int
data-type can contain";
[Link]([Link]("Max|max|MAX","MIN"));
// Above code Prints "MINimum value of INT_MIN is MINimum value that int data-type
can contain"
// It replaces all occurrences of Max or max or MAX
// Read regex for using this properly
[Link]("\n\nThe split() method");
String sentence = "This is a sentence that contains punctuation marks. " +
"Thus, one should parse it carefully.";
String[] words = [Link]("[\\W]+",0); // limit = 0, apply delimiter
// as many times as possible
// and discard TRAILING EMPTY STRINGS
// The above split() takes delimiter as one or more NON-WORD CHARACTERS (anything
except A-Z,a-z,0-9 and _ )
// Regex Metacharacters for regex X
// X? - Zero or one appearance of X
// X* - Zero or more appearance of X
// X+ - One or more appearance of X
// X{n} - n appearances of X
// X{n,} - n or more appearances of X
// X{n,m} - n or more but less than m appearances of X
// Regex finder
// . = Any character
// \d = Any digits = [0-9] ( Note that you have to write "\\d" when using in a string
// \D = Any NON-DIGIT = [^0-9]
// \s = Whitespace character [\t\n\x0B\f\r]
// \S = NON-WHITESPACE CHARACTER [^\s]
// \w = Any word character [a-zA-Z_0-9]
// \W = Non-word character [^\w]
// \b = Word boundary
// \B = Non-word boundary
for(String word:words){
[Link](word); // Display each word from array of words
}
String sentence2 = "A sentence with 4 spaces";
String[] str_arr1 = [Link]("\\s",2); // Apply delimiter 1 or limit-1 times only
[Link]([Link](str_arr1)); // Prints [A, sentence with 4 spaces]
String sentence3WithHyphens = "I-am-thinking---";
str_arr1 = [Link]("-",3); // Apply delimiter 2 times or (limit-1) times
[Link]([Link](str_arr1)); // Prints [I, am, thinking---]
str_arr1 = [Link]("-",-2); // Apply delimiter as many times as
possible
// And keep the trailing empty strings
[Link]([Link](str_arr1)); // Prints [I, am, thinking, , , ] (3 empty strings
at the end)
str_arr1 = [Link]("-",0); // Apply delimiter as many times as
possible
// And DISCARD the trailing empty strings
[Link]([Link](str_arr1)); // Prints [I, am, thinking]
str_arr1 = [Link]("-",0); // Returns array of strings
and the delimiters
[Link]([Link](str_arr1)); // Prints [I, -, am, -, thinking, -, , -, , -]
str_arr1 = [Link]("-",-1); // Returns array of strings
and the delimiters
[Link]([Link](str_arr1)); // Prints [I, -, am, -, thinking, -, , -, , -, ]
[Link]("\n\nThe lines() method :");
String multiline = "This is first line.\n" +
"This is second line.\n" +
"This is third line.\n";
// lines() separates lines using line separators which are '\n', '\r' (Carriage return), "\r\n"
Stream<String> lines = [Link](); // Get a Stream<String> of lines
[Link]([Link]::println); // Print each line in the stream
[Link]("\n\nThe join() method :");
List<String> wordList = [Link]("My","name","is","Barry","Allen");
String sentenceFromWordList = [Link](" ",wordList); // Takes a delimiter and Iterable
[Link](sentenceFromWordList); // Prints "My name is Barry Allen"
String sentenceFromWords = [Link](" ","This","is","list","of","words"); // Can take
CharSequence
// to join directly
[Link](sentenceFromWords); // Prints "This is list of words"
String sentenceFromStringArray = [Link](" ",words); // Can take delimiter and an
array of CharSequence
[Link](sentenceFromStringArray);
// Above statement prints "This is a sentence that contains punctuation marks Thus one
should parse it carefully"
[Link]("\n\nThe getChars() method :");
char[] charArray = new char[25];
[Link](0, [Link](),charArray,0);
[Link]([Link](charArray));
// The above statement prints:
// [W, e, l, c, o, m, e, , t, o, , U, p, g, r, a, d, , C, a, m, p, u, s,\u0000 ]
// \u0000 is null character (default values for char array elements) [output will show this
with a symbol]
[Link]("\n\nThe toCharArray() method :");
// toCharArray() converts String to character array
char[] arrayFromString = [Link]();
char[] charArray2 = new char[30];
[Link](0, [Link](),charArray2,6); // Starts filling the
array up from index 6
[Link]([Link](charArray2));
[Link]("\n\nThe trim() and strip() method :");
[Link]("\nNote: Space is defined any character whose value is less than or
equal to \\u+0020");
[Link]("\nNote: \\u+0020 is Unicode for space");
String stringWithLeadingSpaces = " A String with leading spaces.";
String stringWithTrailingSpaces = "A String with trailing spaces. ";
String stringWithSpacesOnBothSides = " A String with leading and trailing spaces. ";
[Link]([Link]()); // Prints "A String with leading
spaces."
[Link]([Link]()); // Prints "A String with trailing
spaces."
[Link]([Link]()); // Prints "A String with leading
and trailing spaces."
[Link]([Link]()); // strip() removes leading/trailing
WhiteSpace Characters
// It checks for whiteSpace using [Link](int codePoint)
[Link]([Link]()); // "A String with leading
and trailing spaces. "
[Link]([Link]()); // " A String with
leading and trailing spaces."
[Link]("\n\nThe equals() and equalsIgnoreCase() method :");
String welcomeString2 = "Welcome to Upgrad Campus";
String welcomeString3 = "Welcome to Upgrad campus"; // c is lowercase in Campus
[Link]([Link](welcomeString3)); // Prints false
[Link]([Link](welcomeString3)); // Prints true
[Link]([Link](welcomeString2)); // Prints true
[Link]("\n\nThe contentEquals() method :");
StringBuffer sb = new StringBuffer("Welcome to Upgrad Campus");
[Link]([Link](sb)); // Prints true
[Link]("\n\nThe compareTo() method :");
String word1 = "Helium";
String word2 = "Helicopter";
String word3 = "Helipad";
String word4 = "Hello";
String word5 = "Hello";
[Link]([Link](word2)); // Prints 18 (positive because word1 >
word2 LEXICOGRAPHICALLY)
[Link]([Link](word3)); // Prints -13 (negative because word2 <
word3 LEXICOGRAPHICALLY)
[Link]([Link](word4)); // Prints -3 (negative because word3 <
word4 LEXICOGRAPHICALLY)
[Link]([Link](word5)); // Prints 0 (because word4 = word5)
[Link]([Link](word1)); // Prints 3 (because word5 > word1
LEXICOGRAPHICALLY)
// word1 > word2 lexicographically means in a dictionary word1 will come AFTER word2
// word1 and word2 have same first 4 letters (H,e,l,i)
// They only differ in 5th characters
[Link]('u'-'c'); // We can use characters as integers. This prints 18
// That is 'u' comes after 18 characters starting from 'c' (c+18 = u)
[Link]((char)('c'+18)); // Prints 'u'
// Similarly, word2 and word3 have equal first 4 letters
[Link]('c'-'p'); // This prints -13
String word6 = "Summer";
String word7 = "Summer Vacation";
[Link]([Link](word7)); // Prints -9 which means word7 > word6
// Lexicographically, these two strings don't differ at any index
// so compareTo returns the difference in length of word6 and word7
// So, in such a case, longer string is lexicographically GREATER (comes after a
dictionary)
[Link]([Link]()-[Link]()); // Prints -9
[Link]("\n\nThe startsWith() and endsWith() methods");
[Link]([Link]("Welc")); // Prints true
[Link]([Link]("welc")); // Prints false (Case sensitive)
[Link]([Link]("Camp")); // Prints false
[Link]([Link]("Camp",17)); // Prints false
[Link]([Link]("Camp",18)); // true (welcomeString starts
with "Camp" from index 18)
[Link]([Link]("us")); // Prints true
[Link]([Link]("Us")); // Prints false (case sensitivity)
[Link]("\n\nThe methods to deal with Unicode Code points :");
[Link](firstCharCodePoint); // Prints 87
[Link]([Link](0)); // Prints 87
String highSurrogateValue = "\uD861";
[Link]([Link](0)); // Prints 55393
// Because \uD861 is HIGH SURROGATE value
// It needs a value in low surrogate range at next index
// Next index is out of bounds
// So, it returns 55393 (decimal for D861 which is hex)
[Link](highSurrogateValue); // Prints ? (question mark) because there is no
character here
String surrogatePair = "\uD861\uDC02";
[Link]([Link]()); // Prints 2 [2 characters but they
// represent a single character together]
[Link]([Link](0)); // Prints 164866
// Now that we have added a LOW SURROGATE value after HIGH SURROGATE VALUE
// This has become a CODE UNIT (surrogate pair)
// This represents a supplementary character in Unicode
[Link](surrogatePair); // Prints this character =>
[Link]([Link](1)); // Prints 87 (code point of W)
[Link]([Link](0,5)); // Prints 5
// There are 5 code points from 0 to 4 (W,e,l,c,o)
[Link]([Link](0,5)); // Prints 5
// Gives index after counting given number of code points. . .
// Here we are counting 5 code points from index 0
// We have code points at 0, 1, 2, 3, 4 (5 code points)
// So, method returns the next index after 5 code points starting from 0
String stringWithSurrogatePairs = "\uD861\uDC02abc";
[Link]([Link](0,2)); // Prints 3
// Note that first two char values form a surrogate pair
// That means these two are a single Unicode code point (supplementary character)
// Thus, to count 2 code points we have code-points at 0,1 ( or \uD861\uDC02) and 2
(a)
// Next index after counting 2 code points is 3
String stringWithOnlyHighSurrogate = "\uD861\u0020abc"; // \u0020 is Unicode for space
[Link]([Link](0,2)); // Prints 2
// Note that \uD861 is an UNPAIRED HIGH SURROGATE and will be counted as 1 code
point
// Then we have another code point \u0020 at index 1
// So, after counting two code points (at index 0 and index 1), the next index is 2
[Link]("ABC_".repeat(5)); // Create string by repeating "ABC_" 5 times:
ABC_ABC_ABC_ABC_ABC_
}/**/
}