Convert String to Title Case
You are given any string. Write a code to convert the string to Title Case. Use ' '(single space) as the delimiter in the string.
public String convertToTitle(String string)
Example
1. Test String Has Multiple Words Seperated By Single Space
Input: hello welcome to j2sehunt
Output: Hello Welcome to J2sehunt
2. Test String already in Title Case. In such case Input and Output remains same.
Input: Hello Welcome to J2sehunt
Output: Hello Welcome to J2sehunt
3. Test String where String With Words Having First Letter In Small Case And Few Or All Letters In Capital Case
Input: hELLO wELCOME tO j2SEHUNT
Output: Hello Welcome to J2sehunt
package com.blogspot.j2sehunt;
public class Client {
/**
* @param args
*/
public String convertToTitle(String string) {
String result = "";
for(int i = 0; i < string.length(); i++) {
String next = string.substring(i, i+1);
if(i == 0) {
result += next.toUpperCase();
} else {
if(string.charAt(i-1)== ' ') {
result += next.toUpperCase();
} else {
result += next.toLowerCase();
}
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Client c = new Client();
System.out.println(c.convertToTitle("wel come to Java"));
System.out.println(c.convertToTitle("hello welcome to j2sehunt"));
System.out.println(c.convertToTitle("Hello Welcome to J2sehunt"));
System.out.println(c.convertToTitle("hELLO wELCOME tO j2SEHUNT"));
}
}
public class Client {
/**
* @param args
*/
public String convertToTitle(String string) {
String result = "";
for(int i = 0; i < string.length(); i++) {
String next = string.substring(i, i+1);
if(i == 0) {
result += next.toUpperCase();
} else {
if(string.charAt(i-1)== ' ') {
result += next.toUpperCase();
} else {
result += next.toLowerCase();
}
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Client c = new Client();
System.out.println(c.convertToTitle("wel come to Java"));
System.out.println(c.convertToTitle("hello welcome to j2sehunt"));
System.out.println(c.convertToTitle("Hello Welcome to J2sehunt"));
System.out.println(c.convertToTitle("hELLO wELCOME tO j2SEHUNT"));
}
}
No comments:
Post a Comment