Learn Selenium and Java for Selenium

Sunday, 10 June 2018

Strings in Java : Part 4

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.

  • 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



Related Posts:

  • Strings in Java : Part 4 String Methods As we know that string class has variety of methods for String manipulation. We would be explaining the mostly used methods available… Read More
  • GIT in Practical World GIT in Practical World We have discussed about meaning of different GIT commands. Now biggest challenge is how exactly GIT is being used in ou… Read More
  • What is Maven? Maven is a build automation tool. With Maven we can import all libraries and can also create project structures.  A Maven is basically a tool … Read More
  • GIT Introduction GIT Introduction Any automation testing project, we need to develop around 100 + testcases in the limited span of time. It is impossible if you… Read More
  • Strings in Java : Part 5 String Methods Continuing with commonly used method in the stings we are covering here charAt()  method is more detailed manner. String char… Read More

0 comments:

Post a Comment

Popular Posts

Recent Posts



Newsletter

Join our newsletter to get secret tips directly in your inbox!


*We Hate Spam!

Powered by Blogger.