Differentiate between CharAt and substring with examples
Answers
Answer:
Hope this answer helps uh...
Answer:
I hope it helpful for you have a great day
Explanation:
The charAt() method of the String class returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
The indexOf(int ch, int fromIndex) method of the String class returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
If a character with value ch occurs in the character sequence represented by this String object at an index no smaller than fromIndex, then the index of the first such occurrence is returned.
Example
public class CharAt_IndexOf_Example {
public static void main(String args[]){
String str = "This is tutorialspoint";
System.out.println("Index of letter 't' = "+ str.indexOf('t', 14));
System.out.println("Letter at the index 8 is ::"+str.charAt(8));
}
}
Output
Index of letter 't' = 21
Letter at the index 8 is ::t
The charAt() method is used to get a character at the specified index in the sequence. The index range is [0, length of the sequence - 1].
Syntax of charAt() method:
public char charAt(int index)
The setCharAt() method is used to set a character at the specified index. The sequence is identical except that it sets the specified character at the specified index.
Syntax of setCharAt() method:
public void setCharAt(int index, char ch)
Note that setCharAt method alter the characters in the sequence, it does not append characters to the sequence.
Here is an example program implementing these methods:
StringBuffer charAt and setCharAt
CODE
Try it Online
class CharAtAndSetCharAtDemo
{
public static void main(String arg[])
{
StringBuffer sb = new StringBuffer("'Happy New Year!'");
for (int i = 0; i < sb.length(); i++)
{
System.out.print(sb.charAt(i)); // LINE A
}
System.out.println();
sb.setCharAt(sb.length() - 1, '"'); // LINE B
sb.setCharAt(0, '"'); // LINE C
System.out.println(sb);
}
}