Write a java program to count number of char in string

Write a java program to count number of char in string. Write a program to read a string and return an integer based on the following rules.

If the first word and the last word in the String match, then return the number of characters in the word else return sum of the characters in both words. Assume the Strings to be case -sensitive.

The return type (integer) should be based on the above rules.

Input and Output Format:

Input consists of a string with a maximum size of 100 characters.

Output consists of a string.

Refer sample output for formatting specifications.

Sample Input 1:

HOW ARE YOU HOW

 Sample Output 1:

9

Sample Input 2:

HOW ARE YOU

Sample Output 2:

6

package com.demo;
 
import java.util.*;
 
public class Main {
 
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String inpList=sc.nextLine();
System.out.println(calculateWordSum(inpList));
 
}
 
public static int calculateWordSum(String inp) {
int count=0;
String st[]=inp.split(" ");
String s1=st[0];
String slst=st[st.length-1];
if(s1.equals(slst))
{
count=s1.length();
}
else
{
count=s1.length()+slst.length();
}
return count;
}
 
}

Add a Comment

Your email address will not be published. Required fields are marked *

4 × 4 =