String Methods
As we know that string class has variety of methods for String manipulation. We would be explaining the mostly used methods available in string class in detailed manner.
As we know that string class has variety of methods for String manipulation. We would be explaining the mostly used methods available in string class in detailed manner.
- String length()
- The length() method returns the number of characters available in the string.
Considering the following program
public class Main {
public static void main(String[] args) {
String str = "Hello World";
int len = str.length();
System.out.println("The string length of '"+str+"' is: "+len);
}
}
The output of the program would be 11 .
Have you noted the above length() function did calculated the white space as well now you may have a requirement where you do want the white spaces in your program . How to handle this?
public class Main {
public static void main(String[] args) {
String str = "Hello World";
int len = str.replace(" ", "").length(); [Here worried about what does replace method do ? Do not be we have explained it below :D]
System.out.println("The string length of is: "+len);
}
}
The output of the program would be 10
- String Replace()
- The replace method replaces the old character/string with the new set of character or string. The function accepts 2 arguments
- Replace(old char, new char)
public class Main{
public static void main(String args[]){
String s1="Hello World";
String replaceString=s1.replace("Hello ","Happy");//replaces all occurrences of "Hello" to "Happy"
System.out.println(replaceString);
}
}
The output of the program would be HappyWorld
0 comments:
Post a Comment