In: Computer Science
in java
write a program that initializes a String variable with "Welcome to Jac444!". Then, use methods of the String class to examine the string and output a few properties of the string, namely The string by itself The length of the string The first character in the string The last character in the string The first word of the string The last word of the string Make sure that your output also contains how many words exists in the string.
You should save file as main.java in your system.
public class Main {
public int lengthOfString(String a)
{
//for printing length of string
int len = 0;
len=a.length();
return len;
}
public char firstcharOfString(String a)
{
//for printing first charcter in a string
return a.charAt(0);
}
public char lastcharOfString(String a)
{
//for printing last charcter in a string
int i=0;
i=a.length()-1;
return a.charAt(i);
}
public String firstwordOfString(String a)
{
//for printing first word in a string
a= a.substring(0, a.indexOf(" "));
return a;
}
public String lastwordOfString(String a)
{
//for printing last word in a string
a= a.substring(a.lastIndexOf(" ")+1);
return a;
}
public int noofwordOfString(String a)
{
//for printing number of words in a string
int c = 0;
if (!(" ".equals(a.substring(0, 1))) || !(" ".equals(a.substring(a.length() - 1))))
{
for (int i = 0; i < a.length(); i++)
{
if (a.charAt(i) == ' ')
{
c++;
}
}
c = c+ 1;
}
return c; // returns 0 if string sta
}
public static void main(String[] args)
{
String input = "Welcome to Jac444!";
Main m = new Main();
System.out.println("The length of word is " + m.lengthOfString(input));
System.out.println("The first character in the string is "+ m.firstcharOfString(input));
System.out.println("The last character in the string is "+ m.lastcharOfString(input));
System.out.println("The first word in the string is "+ m.firstwordOfString(input));
System.out.println("The last word in the string is "+ m.lastwordOfString(input));
System.out.println("The number of words in the string is "+ m.noofwordOfString(input));
}
}