Extract the difference between two strings in Java - java

Hi I have two strings :
String hear = "Hi My name is Deepak"
+ "\n"
+ "How are you ?"
+ "\n"
+ "\n"
+ "How is everyone";
String dear = "Hi My name is Deepak"
+ "\n"
+ "How are you ?"
+ "\n"
+ "Hey there \n"
+ "How is everyone";
I want to get what is not present in the hear string that is "Hey There \n". I found a method , but it fails for this case :
static String strDiffChop(String s1, String s2) {
if (s1.length() > s2.length()) {
return s1.substring(s2.length() - 1);
} else if (s2.length() > s1.length()) {
return s2.substring(s1.length() - 1);
} else {
return "";
}
}
Can any one help ?

google-diff-match-patch
The Diff Match and Patch libraries offer robust algorithms to perform the operations required for synchronizing plain text.
Diff:
Compare two blocks of plain text and efficiently return a list of differences.
Match:
Given a search string, find its best fuzzy match in a block of plain text. Weighted for both accuracy and location.
Patch:
Apply a list of patches onto plain text. Use best-effort to apply patch even when the underlying text doesn't match.
Currently available in Java, JavaScript, Dart, C++, C#, Objective C, Lua and Python. Regardless of language, each library features the same API and the same functionality. All versions also have comprehensive test harnesses.
There is a Line or word diffs wiki page which describes how to do line-by-line diffs.

One can use the StringUtils from Apache Commons. Here is the StringUtils API.
public static String difference(String str1, String str2) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
int at = indexOfDifference(str1, str2);
if (at == -1) {
return EMPTY;
}
return str2.substring(at);
}
public static int indexOfDifference(String str1, String str2) {
if (str1 == str2) {
return -1;
}
if (str1 == null || str2 == null) {
return 0;
}
int i;
for (i = 0; i < str1.length() && i < str2.length(); ++i) {
if (str1.charAt(i) != str2.charAt(i)) {
break;
}
}
if (i < str2.length() || i < str1.length()) {
return i;
}
return -1;
}

I have used the StringTokenizer to find the solution. Below is the code snippet
public static List<String> findNotMatching(String sourceStr, String anotherStr){
StringTokenizer at = new StringTokenizer(sourceStr, " ");
StringTokenizer bt = null;
int i = 0, token_count = 0;
String token = null;
boolean flag = false;
List<String> missingWords = new ArrayList<String>();
while (at.hasMoreTokens()) {
token = at.nextToken();
bt = new StringTokenizer(anotherStr, " ");
token_count = bt.countTokens();
while (i < token_count) {
String s = bt.nextToken();
if (token.equals(s)) {
flag = true;
break;
} else {
flag = false;
}
i++;
}
i = 0;
if (flag == false)
missingWords.add(token);
}
return missingWords;
}

convert the string to lists and then use the following method to get result How to remove common values from two array list

If you prefer not to use an external library, you can use the following Java snippet to efficiently compute the difference:
/**
* Returns an array of size 2. The entries contain a minimal set of characters
* that have to be removed from the corresponding input strings in order to
* make the strings equal.
*/
public String[] difference(String a, String b) {
return diffHelper(a, b, new HashMap<>());
}
private String[] diffHelper(String a, String b, Map<Long, String[]> lookup) {
return lookup.computeIfAbsent(((long) a.length()) << 32 | b.length(), k -> {
if (a.isEmpty() || b.isEmpty()) {
return new String[]{a, b};
} else if (a.charAt(0) == b.charAt(0)) {
return diffHelper(a.substring(1), b.substring(1), lookup);
} else {
String[] aa = diffHelper(a.substring(1), b, lookup);
String[] bb = diffHelper(a, b.substring(1), lookup);
if (aa[0].length() + aa[1].length() < bb[0].length() + bb[1].length()) {
return new String[]{a.charAt(0) + aa[0], aa[1]};
} else {
return new String[]{bb[0], b.charAt(0) + bb[1]};
}
}
});
}
This approach is using dynamic programming. It tries all combinations in a brute force way but remembers already computed substrings and therefore runs in O(n^2).
Examples:
String hear = "Hi My name is Deepak"
+ "\n"
+ "How are you ?"
+ "\n"
+ "\n"
+ "How is everyone";
String dear = "Hi My name is Deepak"
+ "\n"
+ "How are you ?"
+ "\n"
+ "Hey there \n"
+ "How is everyone";
difference(hear, dear); // returns {"","Hey there "}
difference("Honda", "Hyundai"); // returns {"o","yui"}
difference("Toyota", "Coyote"); // returns {"Ta","Ce"}

I was looking for some solution but couldn't find the one i needed, so I created a utility class for comparing two version of text - new and old - and getting result text with changes between tags - [added] and [deleted]. It could be easily replaced with highlighter you choose instead of this tags, for example: a html tag. string-version-comparison
Any comments will be appreciated.
*it might not worked well with long text because of higher probability of finding same phrases as deleted.

You should use StringUtils from Apache Commons
String diff = StringUtils.difference( "Word", "World" );
System.out.println( "Difference: " + diff );
Difference: ld
Source: https://www.oreilly.com/library/view/jakarta-commons-cookbook/059600706X/ch02s15.html

My solution is for simple strings.
You can extend it by tokenising lines from a paragraph.
It uses min Edit distance(recursion approach). You can use Dp if you would like.
import java.util.concurrent.atomic.AtomicInteger;
// A Naive recursive Java program to find minimum number
// operations to convert str1 to str2
class JoveoTest {
static int min(int x, int y, int z)
{
if (x <= y && x <= z)
return x;
if (y <= x && y <= z)
return y;
else
return z;
}
static int editDist(String str1, String str2, int m,
int n,StringBuilder str)
{
if (m == 0) {
StringBuilder myStr1=new StringBuilder();
myStr1.append("+"+str2);
myStr1.reverse();
str=myStr1;
return n;
}
if (n == 0){
StringBuilder myStr1=new StringBuilder();
myStr1.append("-"+str1);
myStr1.reverse();
str=myStr1;
return m;
}
if (str1.charAt(m - 1) == str2.charAt(n - 1))
return editDist(str1, str2, m - 1, n - 1,str);
StringBuilder myStr1=new StringBuilder();
StringBuilder myStr2=new StringBuilder();
StringBuilder myStr3=new StringBuilder();
int insert= editDist(str1, str2, m, n - 1,myStr1);
int remove=editDist(str1, str2, m - 1, n,myStr2);
int replace=editDist(str1, str2, m - 1, n-1,myStr3);
if(insert<remove&&insert<replace){
myStr1.insert(0,str2.charAt(n-1)+"+");
str.setLength(0);
str.append(myStr1);
}
else if(remove<insert&&remove<replace){
myStr2.insert(0,str2.charAt(m-1)+"-");
str.setLength(0);
str.append(myStr2);
}
else{
myStr3.insert(0,str2.charAt(n-1)+"+"+str1.charAt(m-1)+"-");
str.setLength(0);
str.append(myStr3);
}
return 1+min(insert,remove,replace);
}
// Driver Code
public static void main(String args[])
{
String str1 = "sunday";
String str2 = "saturday";
StringBuilder ans=new StringBuilder();
System.out.println(editDist(
str1, str2, str1.length(), str2.length(),ans ));
System.out.println(ans.reverse().toString());
}
}
3
+a+t-n+r

what about this snippet ?
public static void strDiff(String hear, String dear){
String[] hr = dear.split("\n");
for (String h : hr) {
if (!hear.contains(h)) {
System.err.println(h);
}
}
}

Related

Replace nested string with some rules

There are 3 rules in the string:
It contains either word or group (enclosed by parentheses), and group can be nested;
If there is a space between word or group, those words or groups should append with "+".
For example:
"a b" needs to be "+a +b"
"a (b c)" needs to be "+a +(+b +c)"
If there is a | between word or group, those words or groups should be surround with parentheses.
For example:
"a|b" needs to be "(a b)"
"a|b|c" needs to be "(a b c)"
Consider all the rules, here is another example:
"aa|bb|(cc|(ff gg)) hh" needs to be "+(aa bb (cc (+ff +gg))) +hh"
I have tried to use regex, stack and recursive descent parser logic, but still cannot fully solve the problem.
Could anyone please share the logic or pseudo code on this problem?
New edited:
One more important rule: vertical bar has higher precedence.
For example:
aa|bb hh cc|dd (a|b) needs to be +(aa bb) +hh +(cc dd) +((a b))
(aa dd)|bb|cc (ee ff)|(gg hh) needs to be +((+aa +dd) bb cc) +((+ee +ff) (+gg +hh))
New edited:
To solve the precedence problem, I find a way to add the parentheses before calling Sunil Dabburi's methods.
For example:
aa|bb hh cc|dd (a|b) will be (aa|bb) hh (cc|dd) (a|b)
(aa dd)|bb|cc (ee ff)|(gg hh) will be ((aa dd)|bb|cc) ((ee ff)|(gg hh))
Since the performance is not a big concern to my application, this way at least make it work for me. I guess the JavaCC tool may solve this problem beautifully. Hope someone else can continue to discuss and contribute this problem.
Here is my attempt. Based on your examples and a few that I came up with I believe it is correct under the rules. I solved this by breaking the problem up into 2 parts.
Solving the case where I assume the string only contains words or is a group with only words.
Solving words and groups by substituting child groups out, use the 1) part and recursively repeating 2) with the child groups.
private String transformString(String input) {
Stack<Pair<Integer, String>> childParams = new Stack<>();
String parsedInput = input;
int nextInt = Integer.MAX_VALUE;
Pattern pattern = Pattern.compile("\\((\\w|\\|| )+\\)");
Matcher matcher = pattern.matcher(parsedInput);
while (matcher.find()) {
nextInt--;
parsedInput = matcher.replaceFirst(String.valueOf(nextInt));
String childParam = matcher.group();
childParams.add(Pair.of(nextInt, childParam));
matcher = pattern.matcher(parsedInput);
}
parsedInput = transformBasic(parsedInput);
while (!childParams.empty()) {
Pair<Integer, String> childGroup = childParams.pop();
parsedInput = parsedInput.replace(childGroup.fst.toString(), transformBasic(childGroup.snd));
}
return parsedInput;
}
// Transform basic only handles strings that contain words. This allows us to simplify the problem
// and not have to worry about child groups or nested groups.
private String transformBasic(String input) {
String transformedBasic = input;
if (input.startsWith("(")) {
transformedBasic = input.substring(1, input.length() - 1);
}
// Append + in front of each word if there are multiple words.
if (transformedBasic.contains(" ")) {
transformedBasic = transformedBasic.replaceAll("( )|^", "$1+");
}
// Surround all words containing | with parenthesis.
transformedBasic = transformedBasic.replaceAll("([\\w]+\\|[\\w|]*[\\w]+)", "($1)");
// Replace pipes with spaces.
transformedBasic = transformedBasic.replace("|", " ");
if (input.startsWith("(") && !transformedBasic.startsWith("(")) {
transformedBasic = "(" + transformedBasic + ")";
}
return transformedBasic;
}
Verified with the following test cases:
#ParameterizedTest
#CsvSource({
"a b,+a +b",
"a (b c),+a +(+b +c)",
"a|b,(a b)",
"a|b|c,(a b c)",
"aa|bb|(cc|(ff gg)) hh,+(aa bb (cc (+ff +gg))) +hh",
"(aa(bb(cc|ee)|ff) gg),(+aa(bb(cc ee) ff) +gg)",
"(a b),(+a +b)",
"(a(c|d) b),(+a(c d) +b)",
"bb(cc|ee),bb(cc ee)",
"((a|b) (a b)|b (c|d)|e),(+(a b) +((+a +b) b) +((c d) e))"
})
void testTransformString(String input, String output) {
Assertions.assertEquals(output, transformString(input));
}
#ParameterizedTest
#CsvSource({
"a b,+a +b",
"a b c,+a +b +c",
"a|b,(a b)",
"(a b),(+a +b)",
"(a|b),(a b)",
"a|b|c,(a b c)",
"(aa|bb cc|dd),(+(aa bb) +(cc dd))",
"(aa|bb|ee cc|dd),(+(aa bb ee) +(cc dd))",
"aa|bb|cc|ff gg hh,+(aa bb cc ff) +gg +hh"
})
void testTransformBasic(String input, String output) {
Assertions.assertEquals(output, transformBasic(input));
}
I tried to solve the problem. Not sure if it works in all cases. Verified with the inputs given in the question and it worked fine.
We need to format the pipes first. That will help add necessary parentheses and spacing.
The spaces generated as part of pipe processing can interfere with actual spaces that are available in our expression. So used $ symbol to mask them.
To process spaces, its tricky as parantheses need to be processed individually. So the approach I am following is to find a set of parantheses starting from outside and going inside.
So typically we have <left_part><parantheses_code><right_part>. Now left_part can be empty, similary right_part can be empty. we need to handle such cases.
Also, if the right_part starts with a space, we need to add '+' to left_part as per space requirement.
NOTE: I am not sure what's expected of (a|b). If the result should be ((a b)) or (a b). I am going with ((a b)) purely by the definition of it.
Now here is the working code:
public class Test {
public static void main(String[] args) {
String input = "aa|bb hh cc|dd (a|b)";
String result = formatSpaces(formatPipes(input)).replaceAll("\\$", " ");
System.out.println(result);
}
private static String formatPipes(String input) {
while (true) {
char[] chars = input.toCharArray();
int pIndex = input.indexOf("|");
if (pIndex == -1) {
return input;
}
input = input.substring(0, pIndex) + '$' + input.substring(pIndex + 1);
int first = pIndex - 1;
int closeParenthesesCount = 0;
while (first >= 0) {
if (chars[first] == ')') {
closeParenthesesCount++;
}
if (chars[first] == '(') {
if (closeParenthesesCount > 0) {
closeParenthesesCount--;
}
}
if (chars[first] == ' ') {
if (closeParenthesesCount == 0) {
break;
}
}
first--;
}
String result;
if (first > 0) {
result = input.substring(0, first + 1) + "(";
} else {
result = "(";
}
int last = pIndex + 1;
int openParenthesesCount = 0;
while (last <= input.length() - 1) {
if (chars[last] == '(') {
openParenthesesCount++;
}
if (chars[last] == ')') {
if (openParenthesesCount > 0) {
openParenthesesCount--;
}
}
if (chars[last] == ' ') {
if (openParenthesesCount == 0) {
break;
}
}
last++;
}
if (last >= input.length() - 1) {
result = result + input.substring(first + 1) + ")";
} else {
result = result + input.substring(first + 1, last) + ")" + input.substring(last);
}
input = result;
}
}
private static String formatSpaces(String input) {
if (input.isEmpty()) {
return "";
}
int startIndex = input.indexOf("(");
if (startIndex == -1) {
if (input.contains(" ")) {
String result = input.replaceAll(" ", " +");
if (!result.trim().startsWith("+")) {
result = '+' + result;
}
return result;
} else {
return input;
}
}
int endIndex = startIndex + matchingCloseParenthesesIndex(input.substring(startIndex));
if (endIndex == -1) {
System.out.println("Invalid input!!!");
return "";
}
String first = "";
String last = "";
if (startIndex > 0) {
first = input.substring(0, startIndex);
}
if (endIndex < input.length() - 1) {
last = input.substring(endIndex + 1);
}
String result = formatSpaces(first);
String parenthesesStr = input.substring(startIndex + 1, endIndex);
if (last.startsWith(" ") && first.isEmpty()) {
result = result + "+";
}
result = result + "("
+ formatSpaces(parenthesesStr)
+ ")"
+ formatSpaces(last);
return result;
}
private static int matchingCloseParenthesesIndex(String input) {
int counter = 1;
char[] chars = input.toCharArray();
for (int i = 1; i < chars.length; i++) {
char ch = chars[i];
if (ch == '(') {
counter++;
} else if (ch == ')') {
counter--;
}
if (counter == 0) {
return i;
}
}
return -1;
}
}

replacing pi with 3.14 in a String recursively (no loops)

Given a string, compute recursively (no loops) a new string where all appearances of "pi" have been replaced by "3.14".
changePi("xpix") → "x3.14x"
changePi("pipi") → "3.143.14"
changePi("pip") → "3.14p"
My code worked perfectly but is there any other way (only recursively no loops) to do this problem without having to create a new string str2 ?
Thank you in advance
here is my code :
public String changePi(String str) {
String str2 = "";
return changePi(str, str2);
}
public String changePi(String str, String str2) {
if (str.length() == 0)
return str2;
else {
if (str.endsWith("pi")) {
str2 = 3.14 + str2;
return changePi(str.substring(0, str.length() - 2), str2);
} else
str2 = str.charAt(str.length() - 1) + str2;
}
return changePi(str.substring(0, str.length() - 1), str2);
}
Using the same mechanism you can use a StringBuilder and modify it in-situ. This should be much more memory efficient.
private static final String PI = "pi";
private static final String THREE_POINT_ONE_FOUR = "3.14";
public String changePi(String s) {
// Work with a StringBuilder for efficiency.
StringBuilder sb = new StringBuilder(s);
// Start replacement at 0.
return changePi(sb, 0).toString();
}
private StringBuilder changePi(StringBuilder sb, int i) {
// Long enough?
if (i + PI.length() <= sb.length()) {
// Is it there?
if (sb.subSequence(i, i + PI.length()).equals(PI)) {
// Yes! - Replace it and recurse.
sb.replace(i, i + PI.length(), THREE_POINT_ONE_FOUR);
return changePi(sb, i + THREE_POINT_ONE_FOUR.length());
} else {
// Not there - step to next.
return changePi(sb, i + 1);
}
}
return sb;
}
private void test(String s) {
System.out.println(s + " -> " + changePi(s));
}
private void test() {
test("pipi");
test("xpix");
test("pip");
}
You are doing the same mistake as you did in your previous question. Also I would prefer to check if a string starts with, and not ends with a string...I am assuming that you would like something that you can understand and it's easy to explain.
Can you match "pi" or the string is already less than length("pi") symbols -> cant do nothing much so return it.
Does it starts with "pi"? If so return the replacement concatenated with the rest of the string (just the rest starts length("pi") characters away from the 0th index...
If it isn't starting with "pi" than concatenate the first character with what's the output of changePi and the rest of the string as its input.
public static String changePi(String str) {
if (str.length() < "pi".length()) {
return str;
}
if (str.startsWith("pi")) {
return "3.14" + changePi(str.substring("pi".length(), str.length()));
}
return str.charAt(0) + changePi(str.substring(1, str.length()));
}
And still if you like to use the "endsWith" logic then here is the same algorythm applied.
public static String changePi(String str) {
if (str.length() < "pi".length()) {
return str;
}
if (str.endsWith("pi")) {
return changePi(str.substring(0, str.length() - "pi".length())) + "3.14";
}
return changePi(str.substring(0, str.length() - 1)) + str.charAt(str.length() - 1);
}
public static String changePi(String str) {
int num = str.indexOf("pi");
if (num==-1) return str;
return str.substring(0,num)+"3.14"+changePi(str.substring(num+2));
}
does it, though I guess it depends what you mean by create a new string. In a sense this does, but without naming it.
Your solution is a nice approach (it's a little confusing as you replace twice, I believe) and I would make sth like:
If str <= than 2, check str if equals pi, return 3,14 or str
Else, if ends with pi return Change(str-2)+Change(last2), else return Change(str-1)+Change(lastChar)
Edited: now changes pi for 3,14
Voila! simple and clean:
String fun(int i) {
if(i == s.length()) return "";
if(i+1 < s.length() && s.charAt(i) == 'p' && s.charAt(i+1) == 'i') {
return "3.14" + fun(i+2);
} else {
return s.charAt(i) + fun(i+1);
}
}
Any reason why you have not considered using regular expressions?
The following seems to work fine for all the test cases you mentioned:
public String changePi(String str) {
return str.replaceAll("pi", "3.14");
}
Note that in Java a String is immutable. You cannot modify a String once you initialise it. Each time you are doing str2 = ... you are really creating a completely new String object.
If you need to do it recursively (i.e. it is some coursework), then what you did is perfectly fine (although I would have used indexOf("pi") rather than endsWith("pi") and removing the trailing characters, but anyway.
It is the standard way to perform recursion, with str2 being the accumulator (maybe you want to rename it so that it is clear what it is doing). You might want to consider using StringBuilder instead of a String for the second parameter, and in your base case you call toString() to get the final string... although honestly the difference in computation cost between creating a new String and using a StringBuilder has become very low.
I've never written Java before, but this seems to work:
public class HelloWorld {
public static void main(String[] args) {
System.out.println(changePi("xpix"));
System.out.println(changePi("pipi"));
System.out.println(changePi("pip"));
}
public static String changePi(String str) {
int len = str.length();
if (len < 2)
return str;
if (str.endsWith("pi"))
return changePi(str.substring(0, len - 2)) + "3.14";
else
return changePi(str.substring(0, len - 1)) + str.substring(len - 1, len);
}
}
Explaination:
This is closer to a true recursive solution, since the function doesn't know about the right portion of the string (no str2), it's the calling function's responsibility to keep track of it.
The terminal case is running on a string shorter than "pi", in which case we return the remainder (0 or 1 chars).
If the string ends in "pi", we take the rest of the string before that and pass that to the new iteration, but keep in mind to append "3.14" when that returns.
If the string doesn't end in that, we just break off a single character and keep it to reattach.
Criticism:
This is horribly inefficient, though, as every .substr call is creating a whole new string object, and we do a lot of these calls.
You would have better luck using something like a linked list of characters.
public String changePi(String str) {
if(str.length() == 0){
return str;
}
if(str.startsWith("pi")){
return "3.14" + changePi(str.substring(2));
}
return str.substring(0,1) + changePi(str.substring(1));
}
public class ChangePi {
public static String changePi(String str) {
String pi = "3.14";
if (str.length() < 2) {
return str;
}
return (str.substring(0, 2).equals("pi")) ? pi + changePi(str.substring(2)) :
str.substring(0, 1) + changePi(str.substring(1));
}
}
Hope my answer explains everything :)
public String changePi(String str) {
if (str.length() < 1) return ""; // return if string length is zero
String count = str.substring(0,1); // get the string
int increment = 1; // increment variable to iterate the string
if (str.length() > 1 && str.substring(0, 2).equals("pi")){
//string length > 1 and it pi if found
count = "3.14";
increment = 2;//increment by 2 characters
}
//attach the 3.14 part or substring(0,1) and move forward in the string
return count + changePi(str.substring(increment));
}
Here is the answer:
public String changePi(String str) {
if(str.equals("")){
return str;
}
else if(str.length()>=2 && str.charAt(0)=='p' && str.charAt(1)=='i') {
return "3.14" + changePi(str.substring(2));
}
else{
return str.charAt(0) + changePi(str.substring(1));
}
}
public String changePi(String str) {
if(str.length() == 0) return str;
if(str.charAt(0) == 'p' && str.length() >= 2){
if(str.charAt(1) == 'i'){
return "3.14" + changePi(str.substring(2));
}
}
return str.charAt(0) + changePi(str.substring(1));
}

Recursively decompressing a String

I have this assignment that needs me to decompress a previously compressed string.
Examples of this would be
i4a --> iaaaa
q3w2ai2b --> qwwwaaibb
3a --> aaa
Here's what I've written so far:
public static String decompress(String compressedText)
{
char c;
char let;
int num;
String done = "";
String toBeDone = "";
String toBeDone2 = "";
if(compressedText.length() <= 1)
{
return compressedText;
}
if (Character.isLetter(compressedText.charAt(0)))
{
done = compressedText.substring(0,1);
toBeDone = compressedText.substring(1);
return done + decompress(toBeDone);
}
else
{
c = compressedText.charAt(0);
num = Character.getNumericValue(c);
let = compressedText.charAt(1);
if (num > 0)
{
num--;
toBeDone = num + Character.toString(let);
toBeDone2 = compressedText.substring(2);
return Character.toString(let) + decompress(toBeDone) + decompress(toBeDone2);
}
else
{
toBeDone2 = compressedText.substring(2);
return Character.toString(let) + decompress(toBeDone2);
}
}
}
My return values are absolutely horrendous.
"ab" yields "babb" somehow.
"a" or any 1 letter string string yields the right result
"2a" yields "aaaaaaaaaaa"
"2a3b" gives me "aaaabbbbbbbbbbbbbbbbbbbbbbbbbbaaabbbbaaaabbbbbbbbbbbbbbbbbbbbbbbbbb"
The only place I can see a mistake in would probably be the last else section, since I wasn't entirely sure on what to do once the number reaches 0 and I have to stop using recursion on the letter after it. Other than that, I can't really see a problem that gives such horrifying outputs.
I reckon something like this would work:
public static String decompress(String compressedText) {
if (compressedText.length() <= 1) {
return compressedText;
}
char c = compressedText.charAt(0);
if (Character.isDigit(c)) {
return String.join("", Collections.nCopies(Character.digit(c, 10), compressedText.substring(1, 2))) + decompress(compressedText.substring(2));
}
return compressedText.charAt(0) + decompress(compressedText.substring(1));
}
As you can see, the base case is when the compressed String has a length less than or equal to 1 (as you have it in your program).
Then, we check if the first character is a digit. If so, we substitute in the correct amount of characters, and continue with the recursive process until we reach the base case.
If the first character is not a digit, then we simply append it and continue.
Keep in mind that this will only work with numbers from 1 to 9; if you require higher values, let me know!
EDIT 1: If the Collections#nCopies method is too complex, here is an equivalent method:
if (Character.isDigit(c)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Character.digit(c, 10); i++) {
sb.append(compressedText.charAt(1));
}
return sb.toString() + decompress(compressedText.substring(2));
}
EDIT 2: Here is a method that uses a recursive helper-method to repeat a String:
public static String decompress(String compressedText) {
if (compressedText.length() <= 1) {
return compressedText;
}
char c = compressedText.charAt(0);
if (Character.isDigit(c)) {
return repeatCharacter(compressedText.charAt(1), Character.digit(c, 10)) + decompress(compressedText.substring(2));
}
return compressedText.charAt(0) + decompress(compressedText.substring(1));
}
public static String repeatCharacter(char character, int counter) {
if (counter == 1) {
return Character.toString(character);
}
return character + repeatCharacter(character, counter - 1);
}

Checking if a string matches all characters but one of another string

I have a list of strings and with each string I want to check it's characters against every other string to see if all it's characters are identical except for one.
For instance a check that would return true would be checking
rock against lock
clock and flock have one character that is different, no more no less.
rock against dent will obviously return false.
I have been thinking about first looping through the list and then having a secondary loop within that one to check the first string against the second.
And then using split(""); to create two arrays containing the characters of each string and then checking the array elements against each other (i.e. comparing each string with the same position in the other array 1-1 2-2 etc...) and so long as only one character comparison fails then the check for those two strings is true.
Anyway I have a lot of strings (4029) and considering what I am thinking of implementing at the moment would contain 3 loops each within the other that would result in a cubic loop(?) which would take a long long time with that many elements wouldn't it?
Is there an easier way to do this? Or will this method actually work okay? Or -hopefully not- but is there some sort of potential logical flaw in the solution I have proposed?
Thanks a lot!
Why not do it the naive way?
bool matchesAlmost(String str1, String str2) {
if (str1.length != str2.length)
return false;
int same = 0;
for (int i = 0; i < str1.length; ++i) {
if (str1.charAt(i) == str2.charAt(i))
same++;
}
return same == str1.length - 1;
}
Now you can just use a quadratic algorithm to check every string against every other.
Assuming the length of two strings are equal
String str1 = "rock";
String str2 = "lick";
if( str1.length() != str2.length() )
System.out.println( "failed");
else{
if( str2.contains( str1.substring( 0, str1.length()-1)) || str2.contains( str1.substring(1, str1.length() )) ){
System.out.println( "Success ");
}
else{
System.out.println( "Failed");
}
}
Not sure if this is the best approach but this one works even when two strings are not of same length. For example : cat & cattp They differ by one character p and t is repeated. Looks like O(n) time solution using additional space for hashmap & character arrays.
/**
* Returns true if two strings differ by one character
* #param s1 input string1
* #param s2 input string2
* #return true if strings differ by one character
*/
boolean checkIfTwoStringDifferByOne(String s1, String s2) {
char[] c1, c2;
if(s1.length() < s2.length()){
c1 = s1.toCharArray();
c2 = s2.toCharArray();
}else{
c1 = s2.toCharArray();
c2 = s1.toCharArray();
}
HashSet<Character> hs = new HashSet<Character>();
for (int i = 0; i < c1.length; i++) {
hs.add(c1[i]);
}
int count = 0;
for (int j = 0; j < c2.length; j++) {
if (! hs.contains(c2[j])) {
count = count +1;
}
}
if(count == 1)
return true;
return false;
}
Assuming that all the strings have the same length, I think this would help:
public boolean differByOne(String source, String destination)
{
int difference = 0;
for(int i=0;i<source.length();i++)
{
if(source.charAt(i)!=destination.charAt(i))
{
difference++;
if(difference>1)
{
return false;
}
}
}
return difference == 1;
}
Best way is to concatenate strings together one forward and other one in reverse order. Then check in single loop for both ends matching chars and also start from middle towards ends matching char. If more than 2 chars mismatch break.
If one mismatch stop and wait for the next one to complete if it reaches the same position then it matches otherwise just return false.
public static void main(String[] args) {
New1 x = new New1();
x.setFunc();
}
static void setFunc() {
Set s = new HashSet < Character > ();
String input = " aecd";
String input2 = "abcd";
String input3 = new StringBuilder(input2).reverse().toString();
String input4 = input.concat(input3);
int length = input4.length();
System.out.println(input4);
int flag = 0;
for (int i = 1, j = length - 1; j > i - 1; i++, j--) {
if (input4.charAt(i) != input4.charAt(j)) {
System.out.println(input4.charAt(i) + " doesnt match with " + input4.charAt(j));
if (input4.charAt(i + 1) != input4.charAt(j)) {
System.out.println(input4.charAt(i + 1) + " doesnt match with " + input4.charAt(j));
flag = 1;
continue;
} else if (input4.charAt(i) != input4.charAt(j - 1)) {
System.out.println(input4.charAt(i) + " doesnt match with " + input4.charAt(j - 1));
flag = 1;
break;
} else if (input4.charAt(i + 1) != input4.charAt(j - 1) && i + 1 <= j - 1) {
System.out.println(input4.charAt(i + 1) + " doesnt match with xxx " + input4.charAt(j - 1));
flag = 1;
break;
}
} else {
continue;
}
}
if (flag == 0) {
System.out.println("Strings differ by one place");
} else {
System.out.println("Strings does not match");
}
}

Is there a method for String conversion to Title Case?

Are there any built in methods available to convert a string into Title Case format?
Apache Commons StringUtils.capitalize() or Commons Text WordUtils.capitalize()
e.g: WordUtils.capitalize("i am FINE") = "I Am FINE" from WordUtils doc
There are no capitalize() or titleCase() methods in Java's String class. You have two choices:
using commons lang string utils.
StringUtils.capitalize(null) = null
StringUtils.capitalize("") = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
write (yet another) static helper method toTitleCase()
Sample implementation
public static String toTitleCase(String input) {
StringBuilder titleCase = new StringBuilder(input.length());
boolean nextTitleCase = true;
for (char c : input.toCharArray()) {
if (Character.isSpaceChar(c)) {
nextTitleCase = true;
} else if (nextTitleCase) {
c = Character.toTitleCase(c);
nextTitleCase = false;
}
titleCase.append(c);
}
return titleCase.toString();
}
Testcase
System.out.println(toTitleCase("string"));
System.out.println(toTitleCase("another string"));
System.out.println(toTitleCase("YET ANOTHER STRING"));
outputs:
String
Another String
YET ANOTHER STRING
If I may submit my take on the solution...
The following method is based on the one that dfa posted. It makes the following major change (which is suited to the solution I needed at the time): it forces all characters in the input string into lower case unless it is immediately preceded by an "actionable delimiter" in which case the character is coerced into upper case.
A major limitation of my routine is that it makes the assumption that "title case" is uniformly defined for all locales and is represented by the same case conventions I have used and so it is less useful than dfa's code in that respect.
public static String toDisplayCase(String s) {
final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
// to be capitalized
StringBuilder sb = new StringBuilder();
boolean capNext = true;
for (char c : s.toCharArray()) {
c = (capNext)
? Character.toUpperCase(c)
: Character.toLowerCase(c);
sb.append(c);
capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
}
return sb.toString();
}
TEST VALUES
a string
maRTin o'maLLEY
john wilkes-booth
YET ANOTHER STRING
OUTPUTS
A String
Martin O'Malley
John Wilkes-Booth
Yet Another String
Use WordUtils.capitalizeFully() from Apache Commons.
WordUtils.capitalizeFully(null) = null
WordUtils.capitalizeFully("") = ""
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
You can use apache commons langs like this :
WordUtils.capitalizeFully("this is a text to be capitalize")
you can find the java doc here :
WordUtils.capitalizeFully java doc
and if you want to remove the spaces in between the worlds you can use :
StringUtils.remove(WordUtils.capitalizeFully("this is a text to be capitalize")," ")
you can find the java doc for String
StringUtils.remove java doc
i hope this help.
If you want the correct answer according to the latest Unicode standard, you should use icu4j.
UCharacter.toTitleCase(Locale.US, "hello world", null, 0);
Note that this is locale sensitive.
Api Documentation
Implementation
Here's another take based on #dfa's and #scottb's answers that handles any non-letter/digit characters:
public final class TitleCase {
public static String toTitleCase(String input) {
StringBuilder titleCase = new StringBuilder(input.length());
boolean nextTitleCase = true;
for (char c : input.toLowerCase().toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
nextTitleCase = true;
} else if (nextTitleCase) {
c = Character.toTitleCase(c);
nextTitleCase = false;
}
titleCase.append(c);
}
return titleCase.toString();
}
}
Given input:
MARY ÄNN O’CONNEŽ-ŠUSLIK
the output is
Mary Änn O’Connež-Šuslik
This is something I wrote to convert snake_case to lowerCamelCase but could easily be adjusted based on the requirements
private String convertToLowerCamel(String startingText)
{
String[] parts = startingText.split("_");
return parts[0].toLowerCase() + Arrays.stream(parts)
.skip(1)
.map(part -> part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
.collect(Collectors.joining());
}
Using Spring's StringUtils:
org.springframework.util.StringUtils.capitalize(someText);
If you're already using Spring anyway, this avoids bringing in another framework.
Use this method to convert a string to title case :
static String toTitleCase(String word) {
return Stream.of(word.split(" "))
.map(w -> w.toUpperCase().charAt(0)+ w.toLowerCase().substring(1))
.reduce((s, s2) -> s + " " + s2).orElse("");
}
I know this is older one, but doesn't carry the simple answer, I needed this method for my coding so I added here, simple to use.
public static String toTitleCase(String input) {
input = input.toLowerCase();
char c = input.charAt(0);
String s = new String("" + c);
String f = s.toUpperCase();
return f + input.substring(1);
}
you can very well use
org.apache.commons.lang.WordUtils
or
CaseFormat
from Google's API.
I had this problem and i searched for it
then i made my own method using some java keywords
just need to pass String variable as parameter and get output as proper titled String.
public class Main
{
public static void main (String[]args)
{
String st = "pARVeEN sISHOsIYA";
String mainn = getTitleCase (st);
System.out.println (mainn);
}
public static String getTitleCase(String input)
{
StringBuilder titleCase = new StringBuilder (input.length());
boolean hadSpace = false;
for (char c:input.toCharArray ()){
if(Character.isSpaceChar(c)){
hadSpace = true;
titleCase.append (c);
continue;
}
if(hadSpace){
hadSpace = false;
c = Character.toUpperCase(c);
titleCase.append (c);
}else{
c = Character.toLowerCase(c);
titleCase.append (c);
}
}
String temp=titleCase.toString ();
StringBuilder titleCase1 = new StringBuilder (temp.length ());
int num=1;
for (char c:temp.toCharArray ())
{ if(num==1)
c = Character.toUpperCase(c);
titleCase1.append (c);
num=0;
}
return titleCase1.toString ();
}
}
It seems none of the answers format it in the actual title case: "How to Land Your Dream Job", "To Kill a Mockingbird", etc. so I've made my own method. Works best for English languages texts.
private final static Set<Character> TITLE_CASE_DELIMITERS = new HashSet<>();
static {
TITLE_CASE_DELIMITERS.add(' ');
TITLE_CASE_DELIMITERS.add('.');
TITLE_CASE_DELIMITERS.add(',');
TITLE_CASE_DELIMITERS.add(';');
TITLE_CASE_DELIMITERS.add('/');
TITLE_CASE_DELIMITERS.add('-');
TITLE_CASE_DELIMITERS.add('(');
TITLE_CASE_DELIMITERS.add(')');
}
private final static Set<String> TITLE_SMALLCASED_WORDS = new HashSet<>();
static {
TITLE_SMALLCASED_WORDS.add("a");
TITLE_SMALLCASED_WORDS.add("an");
TITLE_SMALLCASED_WORDS.add("the");
TITLE_SMALLCASED_WORDS.add("for");
TITLE_SMALLCASED_WORDS.add("in");
TITLE_SMALLCASED_WORDS.add("on");
TITLE_SMALLCASED_WORDS.add("of");
TITLE_SMALLCASED_WORDS.add("and");
TITLE_SMALLCASED_WORDS.add("but");
TITLE_SMALLCASED_WORDS.add("or");
TITLE_SMALLCASED_WORDS.add("nor");
TITLE_SMALLCASED_WORDS.add("to");
}
public static String toCapitalizedWord(String oneWord) {
if (oneWord.length() < 1) {
return oneWord.toUpperCase();
}
return "" + Character.toTitleCase(oneWord.charAt(0)) + oneWord.substring(1).toLowerCase();
}
public static String toTitledWord(String oneWord) {
if (TITLE_SMALLCASED_WORDS.contains(oneWord.toLowerCase())) {
return oneWord.toLowerCase();
}
return toCapitalizedWord(oneWord);
}
public static String toTitleCase(String str) {
StringBuilder result = new StringBuilder();
StringBuilder oneWord = new StringBuilder();
char previousDelimiter = 'x';
/* on start, always move to upper case */
for (char c : str.toCharArray()) {
if (TITLE_CASE_DELIMITERS.contains(c)) {
if (previousDelimiter == '-' || previousDelimiter == 'x') {
result.append(toCapitalizedWord(oneWord.toString()));
} else {
result.append(toTitledWord(oneWord.toString()));
}
oneWord.setLength(0);
result.append(c);
previousDelimiter = c;
} else {
oneWord.append(c);
}
}
if (previousDelimiter == '-' || previousDelimiter == 'x') {
result.append(toCapitalizedWord(oneWord.toString()));
} else {
result.append(toTitledWord(oneWord.toString()));
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(toTitleCase("one year in paris"));
System.out.println(toTitleCase("How to Land Your Dream Job"));
}
This is the simplest solution
static void title(String a,String b){
String ra = Character.toString(Character.toUpperCase(a.charAt(0)));
String rb = Character.toString(Character.toUpperCase(b.charAt(0)));
for(int i=1;i<a.length();i++){
ra+=a.charAt(i);
}
for(int i=1;i<b.length();i++){
rb+=b.charAt(i);
}
System.out.println(ra+" "+rb);
I recently ran into this problem too and unfortunately had many occurences of names beginning with Mc and Mac, I ended up using a version of scottb's code which I changed to handle these prefixes so it's here in case anyone wants to use it.
There are still edge cases which this misses but the worst thing that can happen is that a letter will be lower case when it should be capitalized.
/**
* Get a nicely formatted representation of the name.
* Don't send this the whole name at once, instead send it the components.<br>
* For example: andrew macnamara would be returned as:<br>
* Andrew Macnamara if processed as a single string<br>
* Andrew MacNamara if processed as 2 strings.
* #param name
* #return correctly formatted name
*/
public static String getNameTitleCase (String name) {
final String ACTIONABLE_DELIMITERS = " '-/";
StringBuilder sb = new StringBuilder();
if (name !=null && !name.isEmpty()){
boolean capitaliseNext = true;
for (char c : name.toCharArray()) {
c = (capitaliseNext)?Character.toUpperCase(c):Character.toLowerCase(c);
sb.append(c);
capitaliseNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0);
}
name = sb.toString();
if (name.startsWith("Mc") && name.length() > 2 ) {
char c = name.charAt(2);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,2));
sb.append (name.substring(2,3).toUpperCase());
sb.append (name.substring(3));
name=sb.toString();
}
} else if (name.startsWith("Mac") && name.length() > 3) {
char c = name.charAt(3);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,3));
sb.append (name.substring(3,4).toUpperCase());
sb.append (name.substring(4));
name=sb.toString();
}
}
}
return name;
}
Conversion to Proper Title Case :
String s= "ThiS iS SomE Text";
String[] arr = s.split(" ");
s = "";
for (String s1 : arr) {
s += WordUtils.capitalize(s1.toLowerCase()) + " ";
}
s = s.substring(0, s.length() - 1);
Result : "This Is Some Text"
This converter transform any string containing camel case, white-spaces, digits and other characters to sanitized title case.
/**
* Convert a string to title case in java (with tests).
*
* #author Sudipto Chandra
*/
public abstract class TitleCase {
/**
* Returns the character type. <br>
* <br>
* Digit = 2 <br>
* Lower case alphabet = 0 <br>
* Uppercase case alphabet = 1 <br>
* All else = -1.
*
* #param ch
* #return
*/
private static int getCharType(char ch) {
if (Character.isLowerCase(ch)) {
return 0;
} else if (Character.isUpperCase(ch)) {
return 1;
} else if (Character.isDigit(ch)) {
return 2;
}
return -1;
}
/**
* Converts any given string in camel or snake case to title case.
* <br>
* It uses the method getCharType and ignore any character that falls in
* negative character type category. It separates two alphabets of not-equal
* cases with a space. It accepts numbers and append it to the currently
* running group, and puts a space at the end.
* <br>
* If the result is empty after the operations, original string is returned.
*
* #param text the text to be converted.
* #return a title cased string
*/
public static String titleCase(String text) {
if (text == null || text.length() == 0) {
return text;
}
char[] str = text.toCharArray();
StringBuilder sb = new StringBuilder();
boolean capRepeated = false;
for (int i = 0, prev = -1, next; i < str.length; ++i, prev = next) {
next = getCharType(str[i]);
// trace consecutive capital cases
if (prev == 1 && next == 1) {
capRepeated = true;
} else if (next != 0) {
capRepeated = false;
}
// next is ignorable
if (next == -1) {
// System.out.printf("case 0, %d %d %s\n", prev, next, sb.toString());
continue; // does not append anything
}
// prev and next are of same type
if (prev == next) {
sb.append(str[i]);
// System.out.printf("case 1, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is not an alphabet
if (next == 2) {
sb.append(str[i]);
// System.out.printf("case 2, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is an alphabet, prev was not +
// next is uppercase and prev was lowercase
if (prev == -1 || prev == 2 || prev == 0) {
if (sb.length() != 0) {
sb.append(' ');
}
sb.append(Character.toUpperCase(str[i]));
// System.out.printf("case 3, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is lowercase and prev was uppercase
if (prev == 1) {
if (capRepeated) {
sb.insert(sb.length() - 1, ' ');
capRepeated = false;
}
sb.append(str[i]);
// System.out.printf("case 4, %d %d %s\n", prev, next, sb.toString());
}
}
String output = sb.toString().trim();
output = (output.length() == 0) ? text : output;
//return output;
// Capitalize all words (Optional)
String[] result = output.split(" ");
for (int i = 0; i < result.length; ++i) {
result[i] = result[i].charAt(0) + result[i].substring(1).toLowerCase();
}
output = String.join(" ", result);
return output;
}
/**
* Test method for the titleCase() function.
*/
public static void testTitleCase() {
System.out.println("--------------- Title Case Tests --------------------");
String[][] samples = {
{null, null},
{"", ""},
{"a", "A"},
{"aa", "Aa"},
{"aaa", "Aaa"},
{"aC", "A C"},
{"AC", "Ac"},
{"aCa", "A Ca"},
{"ACa", "A Ca"},
{"aCamel", "A Camel"},
{"anCamel", "An Camel"},
{"CamelCase", "Camel Case"},
{"camelCase", "Camel Case"},
{"snake_case", "Snake Case"},
{"toCamelCaseString", "To Camel Case String"},
{"toCAMELCase", "To Camel Case"},
{"_under_the_scoreCamelWith_", "Under The Score Camel With"},
{"ABDTest", "Abd Test"},
{"title123Case", "Title123 Case"},
{"expect11", "Expect11"},
{"all0verMe3", "All0 Ver Me3"},
{"___", "___"},
{"__a__", "A"},
{"_A_b_c____aa", "A B C Aa"},
{"_get$It132done", "Get It132 Done"},
{"_122_", "122"},
{"_no112", "No112"},
{"Case-13title", "Case13 Title"},
{"-no-allow-", "No Allow"},
{"_paren-_-allow--not!", "Paren Allow Not"},
{"Other.Allow.--False?", "Other Allow False"},
{"$39$ldl%LK3$lk_389$klnsl-32489 3 42034 ", "39 Ldl Lk3 Lk389 Klnsl32489342034"},
{"tHis will BE MY EXAMple", "T His Will Be My Exa Mple"},
{"stripEvery.damn-paren- -_now", "Strip Every Damn Paren Now"},
{"getMe", "Get Me"},
{"whatSthePoint", "What Sthe Point"},
{"n0pe_aLoud", "N0 Pe A Loud"},
{"canHave SpacesThere", "Can Have Spaces There"},
{" why_underScore exists ", "Why Under Score Exists"},
{"small-to-be-seen", "Small To Be Seen"},
{"toCAMELCase", "To Camel Case"},
{"_under_the_scoreCamelWith_", "Under The Score Camel With"},
{"last one onTheList", "Last One On The List"}
};
int pass = 0;
for (String[] inp : samples) {
String out = titleCase(inp[0]);
//String out = WordUtils.capitalizeFully(inp[0]);
System.out.printf("TEST '%s'\nWANTS '%s'\nFOUND '%s'\n", inp[0], inp[1], out);
boolean passed = (out == null ? inp[1] == null : out.equals(inp[1]));
pass += passed ? 1 : 0;
System.out.println(passed ? "-- PASS --" : "!! FAIL !!");
System.out.println();
}
System.out.printf("\n%d Passed, %d Failed.\n", pass, samples.length - pass);
}
public static void main(String[] args) {
// run tests
testTitleCase();
}
}
Here are some inputs:
aCamel
TitleCase
snake_case
fromCamelCASEString
ABCTest
expect11
_paren-_-allow--not!
why_underScore exists
last one onTheList
And my outputs:
A Camel
Title Case
Snake Case
From Camel Case String
Abc Test
Expect11
Paren Allow Not
Why Under Score Exists
Last One On The List
Without dependency -
public static String capitalizeFirstLetter(String s) {
if(s.trim().length()>0){
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
return s;
}
public static String createTitleCase(String s) {
if(s.trim().length()>0){
final StringBuilder sb = new StringBuilder();
String[] strArr = s.split("\\s*");
for(String s1 : strArr) {
sb.append(capitalizeFirstLetter(s1));
}
s = sb.toString();
sb.setLength(0);
}
return s;
}
This should work:
String str="i like pancakes";
String arr[]=str.split(" ");
String strNew="";
for(String str1:arr)
{
Character oldchar=str1.charAt(0);
Character newchar=Character.toUpperCase(str1.charAt(0));
strNew=strNew+str1.replace(oldchar,newchar)+" ";
}
System.out.println(strNew);
The simplest way of converting any string into a title case, is to use googles package org.apache.commons.lang.WordUtils
System.out.println(WordUtils.capitalizeFully("tHis will BE MY EXAMple"));
Will result this
This Will Be My Example
I'm not sure why its named "capitalizeFully", where in fact the function is not doing a full capital result, but anyways, thats the tool that we need.
Sorry I am a beginner so my coding habit sucks!
public class TitleCase {
String title(String sent)
{
sent =sent.trim();
sent = sent.toLowerCase();
String[] str1=new String[sent.length()];
for(int k=0;k<=str1.length-1;k++){
str1[k]=sent.charAt(k)+"";
}
for(int i=0;i<=sent.length()-1;i++){
if(i==0){
String s= sent.charAt(i)+"";
str1[i]=s.toUpperCase();
}
if(str1[i].equals(" ")){
String s= sent.charAt(i+1)+"";
str1[i+1]=s.toUpperCase();
}
System.out.print(str1[i]);
}
return "";
}
public static void main(String[] args) {
TitleCase a = new TitleCase();
System.out.println(a.title(" enter your Statement!"));
}
}

Categories

Resources