Which of these method of class string is used to extract more than one character at a time?
A Brief Summary of the String ClassA Java String contains an immutable sequence of Unicode characters. Unlike C/C++, where string is simply an array of char, A Java String is an object of the class java.lang.String. Show
Java String is, however, special. Unlike an ordinary class:
Method SummaryThe commonly-used method in the String class are summarized below. Refer to the JDK API for java.lang.String a complete listing. int length() boolean isEmpty() boolean isBlank() boolean equals(String another) boolean equalsIgnoreCase(String another) int compareTo(String another) int compareToIgnoreCase(String another) boolean startsWith(String another) boolean startsWith(String another, int fromIdx) boolean endsWith(String another) int indexOf(String key) int indexOf(String key, int fromIdx) int indexOf(int char) int indexOf(int char, int fromIdx) int lastIndexOf(String key) int lastIndexOf(String key, int fromIdx) int lastIndexOf(int char) int lastIndexOf(int char, int fromIdx) char charAt(int idx) String substring(int fromIdx) String substring(int fromIdx, int toIdx) String toLowerCase() String toUpperCase() String concat(String another) String trim() String strip() String stripLeading() String stripTrailing() String repeat(int count) String indent(int n) char[] toCharArray() void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) boolean contains(CharSequence cs) boolean contentEquals(CharSequence cs) boolean contentEquals(StringBuffer sb) static String join(CharSequence delimiter, CharSequence... elements) static String join(CharSequence delimiter, IterableExamplesstatic method String.format() (JDK 5)The static method String.format() (introduced in JDK 5) can be used to produce a formatted String using C-like printf()'s format specifiers. The format() method has the same form as printf(). For example, String.format("%.1f", 1.234);String.format() is useful if you need to produce a simple formatted String for some purposes (e.g., used in method toString()). For complex string, use StringBuffer/StringBuilder with a Formatter. If you simply need to send a simple formatted string to the console, use System.out.printf(), e.g., System.out.printf("%.1f", 1.234);[TODO] More examples New MethodsJDK 9 new methods
JDK 9 new methods
JDK 11 new methods
JDK 12 new methods
JDK 13 new methods
String is Really Special!Strings receive special treatment in Java, because they are used frequently in a program. Hence, efficiency (in terms of computation and storage) is crucial. The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the method stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces. For performance reason, Java's String is designed to be in between a primitive and an object. The special features in String include:
String Literal vs. String ObjectAs mentioned, there are two ways to construct a string: implicit construction by assigning a string literal or explicitly creating a String object via the new operator and constructor. For example, String s1 = "Hello"; String s2 = "Hello"; String s3 = s1; String s4 = new String("Hello"); String s5 = new String("Hello");Java has provided a special mechanism for keeping the String literals - in a so-called string common pool. If two string literals have the same contents, they will share the same storage inside the common pool. This approach is adopted to conserve storage for frequently-used strings. On the other hand, String objects created via the new operator and constructor are kept in the heap. Each String object in the heap has its own storage just like any other object. There is no sharing of storage in heap even if two String objects have the same contents. You can use the method equals() of the String class to compare the contents of two Strings. You can use the relational equality operator '==' to compare the references (or pointers) of two objects. Study the following codes: s1 == s1; s1 == s2; s1 == s3; s1.equals(s3); s1 == s4; s1.equals(s4); s4 == s5; s4.equals(s5);Important Notes:
String is ImmutableSince string literals with the same contents share storage in the common pool, Java's String is designed to be immutable. That is, once a String is constructed, its contents cannot be modified. Otherwise, the other String references sharing the same storage location will be affected by the change, which can be unpredictable and therefore is undesirable. Methods such as toUpperCase() might appear to modify the contents of a String object. In fact, a completely new String object is created and returned to the caller. The original String object will be deallocated, once there is no more references, and subsequently garbage-collected. Because String is immutable, it is not efficient to use String if you need to modify your string frequently (that would create many new Strings occupying new storage areas). For example, String str = "Hello"; for (int i = 1; i < 1000; ++i) { str = str + i; }If the contents of a String have to be modified frequently, use the StringBuffer or StringBuilder class instead. String.intern()[TODO] StringBuffer & StringBuilderAs explained earlier, Strings are immutable because String literals with same content share the same storage in the string common pool. Modifying the content of one String directly may cause adverse side-effects to other Strings sharing the same storage. JDK provides two classes to support mutable strings: StringBuffer and StringBuilder (in core package java.lang). A StringBuffer or StringBuilder object is just like any ordinary object, which are stored in the heap and not shared, and therefore, can be modified without causing adverse side-effect to other objects. StringBuilder class was introduced in JDK 5. It is the same as StringBuffer class, except that StringBuilder is not synchronized for multi-thread operations. However, for single-thread program, StringBuilder, without the synchronization overhead, is more efficient. java.lang.StringBufferRead the JDK API specification for java.lang.StringBuffer. StringBuffer() StringBuffer(int size) StringBuffer(String s) int length() StringBuffer append(type arg) StringBuffer insert(int offset, arg) StringBuffer delete(int fromIdx, int toIdx) StringBuffer deleteCharAt(int idx) void setLength(int newSize) void setCharAt(int idx, char newChar) StringBuffer replace(int fromIdx, int toIdx, String s) StringBuffer reverse() char charAt(int idx) String substring(int fromIdx) String substring(int fromIdx, int toIdx) String toString() int indexOf(String key) int indexOf(String key, int fromIdx) int lastIndexOf(String key) int lastIndexOf(String key, int fromIdx)Take note that StringBuffer is an ordinary object. You need to use a constructor to create a StringBuffer (instead of assigning to a String literal). Furthermore, '+' operator does not apply to objects, including the StringBuffer. You need to use a proper method such as append() or insert() to manipulating a StringBuffer. To create a string from parts, It is more efficient to use StringBuffer (multi-thread) or StringBuilder (single-thread) instead of via String concatenation. For example, int year = 2010, month = 10, day = 10; int hour = 10, minute = 10, second = 10; String dateStr = new StringBuilder() .append(year).append("-").append(month).append("-").append(day).append(" ") .append(hour).append(":").append(minute).append(":").append(second).toString(); System.out.println(dateStr); String anotherDataStr = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; System.out.println(anotherDataStr);JDK compiler, in fact, uses both String and StringBuffer to handle string concatenation via the '+' operator. For examples, String msg = "a" + "b" + "c";will be compiled into the following codes for better efficiency: String msg = new StringBuffer().append("a").append("b").append("c").toString();Two objects are created during the process, an intermediate StringBuffer object and the returned String object. Rule of Thumb: Strings are more efficient if they are not modified (because they are shared in the string common pool). However, if you have to modify the content of a string frequently (such as a status message), you should use the StringBuffer class (or the StringBuilder described below) instead. java.lang.StringBuilder (JDK 5)JDK 5 introduced a new StringBuilder class (in package java.lang), which is almost identical to the StringBuffer class, except that it is not synchronized. In other words, if multiple threads are accessing a StringBuilder instance at the same time, its integrity cannot be guaranteed. However, for a single-thread program (most commonly), doing away with the overhead of synchronization makes the StringBuilder faster. StringBuilder is API-compatible with the StringBuffer class, i.e., having the same set of constructors and methods, but with no guarantee of synchronization. It can be a drop-in replacement for StringBuffer under a single-thread environment. Benchmarking String/StringBuffer/StringBuilderThe following program compare the times taken to reverse a long string via a String object and a StringBuffer.
Observe StringBuilder is 2x faster than StringBuffer, and 300x faster than String. The reverse() method is the fastest, which take about the same time for StringBuilder and StringBuffer. java.util.StringTokenizer (Obsoleted by regex)Very often, you need to break a line of texts into tokens delimited by white spaces. The java.util.StringTokenizer class supports this. For example, the following program reverses the words in a String. import java.util.StringTokenizer; public class StringTokenizerTest { public static void main(String[] args) { String str = "Monday Tuesday Wednesday Thursday Friday Saturday Sunday"; String strReverse; StringBuilder sb = new StringBuilder(); StringTokenizer st = new StringTokenizer(str); while (st.hasMoreTokens()) { sb.insert(0, st.nextToken()); if (st.hasMoreTokens()) { sb.insert(0, " "); } } strReverse = sb.toString(); System.out.println(strReverse); } }StringTokenizer(String s) StrintTokenizer(String s, String delimiterChars) boolean hasNextToken() String nextToken()For example, StringTokenizer tokenizer = new StringTokenizer(aString); while (tokenizer.hasNextToken()) { String token = tokenizer.nextToken(); ..... }The JDK documentation stated that "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split() method of String or the java.util.regex package instead." For example, the following program uses the split() method of the String class to reverse the words of a String. public class StringSplitTest { public static void main(String[] args) { String str = "Monday Tuesday Wednesday Thursday Friday Saturday Sunday"; String[] tokens = str.split("\\s"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length; ++i) { sb.insert(0, tokens[i]); if (i < tokens.length - 1) { sb.insert(0, " "); } } String strReverse = sb.toString(); System.out.println(strReverse); } }Regular Expression (Regex), Patterns & Matches (JDK 4)Read "Regular Expression in Java". Super-Interface CharSequence for String, StringBuffer and StringBuilder (since JDK 4)The interface java.lang.CharSequence is implemented by classes String, StringBuffer, StringBuilder, CharBuffer and Segment. It defines the common behavior via these abstract methods: abstract charAt(int index) -> char abstract length() -> int abstract subSequence(int fromIdx, int toIdx) -> CharSequence abstract toString() -> StringJDK 8 added two default methods into the interface: default chars() -> IntStream default codePoints() -> IntStreamJDK 11 added one static methods into the interface: static compare(CharSequence cs1, CharSequence cs2) -> intLINK TO JAVA REFERENCES & RESOURCES Which of given below of these method of class String is used to extract more than one character at a time a String object?Which of these method of class String is used to extract more than one character at a time a String object? Clarification: None.
Which methods are used to extract the characters from String?Below are various ways to do so:. Using String. charAt() method: Get the string and the index. ... . Using String. toCharArray() method: Get the string and the index. ... . Using Java 8 Streams: Get the string and the index. Convert String into IntStream using String. ... . Using String. codePointAt() method: ... . Using String. getChars() method:. Which method of String class is most appropriate for extracting all the characters of String into an array?char[] toCharArray() : This method converts string to character array. The char array size is same as the length of the string. char charAt(int index) : This method returns character at specific index of string.
Which of these method of class String is used to extract specific String?charAt() is the method of class String is used to extract a single character from a String Object. Hence, option(c) is the correct answer.
|