So, the task is to create a string that makes a progression throughout the letters of a string, returning a substring progressively longer.
For example if the input is Book, the answer would be: BBoBooBook . For the input Soup the method would return SSoSouSoup. I want to write it recursively. In my current method I receive no error but at the same time no anwer from the compiler.
public static String stringProgression(String str) {
int index = 1;
String result = "";
if (str.length() == 0) {
return "" ;
} else while (index <= str.length()); {
result = result + stringExplosion(str.substring(0, index));
index++;
}
return result;
}
In your code, you are using two different method names, stringProgression and stringExplosion.
Further, you have a while loop with a semicolon, while (index <= str.length()); which forms an empty loop. Since index doesn’t change in this empty loop, it will be an infinite loop when the condition is fulfilled.
Generally, a while loop contradicts the intent to have a recursive solution.
To find a recursive solution to a problem, you have to find the self-similarity in it. I.e. when you look at the intended result for Book, BBoBooBook, you can recognize that the beginning, BBoBoo is the right result for the string Boo, and BBo is the right result for Bo. So, the original string has to be appended to the result of a recursive evaluation of the substring:
public static String stringProgression(String str) {
if(str.isEmpty()) {
return str;
}
return stringProgression(str.substring(0, str.length() - 1)) + str;
}
An alternative, shorter syntax for the same is:
public static String stringProgression(String str) {
return str.isEmpty()? str: stringProgression(str.substring(0, str.length() - 1)) + str;
}
Check this one:
private static String doStringProgression(String str, String res, int length) {
if(length > str.length()) {
return res;
}
return doStringProgression(str, res + str.substring(0, length), length + 1);
}
And you can call the method with input like in the following example:
public static String stringProgression(String str) {
return doStringProgression(str, "", 1);
}
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);
}
}
}
I created this method deleteCharAt in order to remove a char from a string by its index:
public String deleteCharAt(String str, int i) {
if (i == 0) {
return str.substring(1);
}
else if (i == str.length()) {
return str.substring(0, i-1);
}
String first = str.substring(0, i - 1);
String second = str.substring(i+1);
return first + second;
}
However it's not working as expected, I think it may be because I'm not understanding how the substring function works.
Does this look correct? Will this code remove the i-th character from a string successfully? Or did I mess up the substring function?
It's not quite right - this:
String first = str.substring(0, i - 1);
should be:
String first = str.substring(0, i);
(Think about a simple example - if i is 1, you want to take substring(0, 1) to get the first character; substring(0, 0) would give an empty string.)
because the second parameter of substring is already exclusive.
Likewise this optimization:
else if (i == str.length()) {
return str.substring(0, i);
}
should be:
else if (i == str.length() - 1) {
return str.substring(0, i);
}
You should also add argument validation.
After making those changes, this code:
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(deleteCharAt("0123456789", i));
}
}
Gives this output:
123456789
023456789
013456789
012456789
012356789
012346789
012345789
012345689
012345679
012345678
public static String deleteCharAt(String s, int pos) {
StringBuffer buf = new StringBuffer( s.length() - 1 );
buf.append( s.substring(0,pos) ).append( s.substring(pos+1) );
return buf.toString();
}
I want to remove the last character from a string. I've tried doing this:
public String method(String str) {
if (str.charAt(str.length()-1)=='x'){
str = str.replace(str.substring(str.length()-1), "");
return str;
} else{
return str;
}
}
Getting the length of the string - 1 and replacing the last letter with nothing (deleting it), but every time I run the program, it deletes middle letters that are the same as the last letter.
For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.
replace will replace all instances of a letter. All you need to do is use substring():
public String method(String str) {
if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
return str;
}
Why not just one liner?
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
Full Code
public class Main {
public static void main (String[] args) throws java.lang.Exception {
String s1 = "Remove Last CharacterY";
String s2 = "Remove Last Character2";
System.out.println("After removing s1==" + removeLastChar(s1) + "==");
System.out.println("After removing s2==" + removeLastChar(s2) + "==");
}
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
}
Demo
Since we're on a subject, one can use regular expressions too
"aaabcd".replaceFirst(".$",""); //=> aaabc
The described problem and proposed solutions sometimes relate to removing separators. If this is your case, then have a look at Apache Commons StringUtils, it has a method called removeEnd which is very elegant.
Example:
StringUtils.removeEnd("string 1|string 2|string 3|", "|");
Would result in:
"string 1|string 2|string 3"
public String removeLastChar(String s) {
if (s == null || s.length() == 0) {
return s;
}
return s.substring(0, s.length()-1);
}
Don't try to reinvent the wheel, while others have already written libraries to perform string manipulation:
org.apache.commons.lang3.StringUtils.chop()
In Kotlin you can used dropLast() method of the string class.
It will drop the given number from string, return a new string
var string1 = "Some Text"
string1 = string1.dropLast(1)
Use this:
if(string.endsWith("x")) {
string= string.substring(0, string.length() - 1);
}
if (str.endsWith("x")) {
return str.substring(0, str.length() - 1);
}
return str;
For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.
In case you're trying to stem English words
Stemming is the process for reducing inflected (or sometimes derived) words to their stem, base or root form—generally a written word form.
...
A stemmer for English, for example, should identify the string "cats" (and possibly "catlike", "catty" etc.) as based on the root "cat", and "stemmer", "stemming", "stemmed" as based on "stem". A stemming algorithm reduces the words "fishing", "fished", "fish", and "fisher" to the root word, "fish".
Difference between Lucene stemmers: EnglishStemmer, PorterStemmer, LovinsStemmer outlines some Java options.
As far as the readability is concerned, I find this to be the most concise
StringUtils.substring("string", 0, -1);
The negative indexes can be used in Apache's StringUtils utility.
All negative numbers are treated from offset from the end of the string.
string = string.substring(0, (string.length() - 1));
I'm using this in my code, it's easy and simple.
it only works while the String is > 0.
I have it connected to a button and inside the following if statement
if (string.length() > 0) {
string = string.substring(0, (string.length() - 1));
}
public String removeLastChar(String s) {
if (!Util.isEmpty(s)) {
s = s.substring(0, s.length()-1);
}
return s;
}
removes last occurence of the 'xxx':
System.out.println("aaa xxx aaa xxx ".replaceAll("xxx([^xxx]*)$", "$1"));
removes last occurrence of the 'xxx' if it is last:
System.out.println("aaa xxx aaa ".replaceAll("xxx\\s*$", ""));
you can replace the 'xxx' on what you want but watch out on special chars
Look to StringBuilder Class :
StringBuilder sb=new StringBuilder("toto,");
System.out.println(sb.deleteCharAt(sb.length()-1));//display "toto"
// creating StringBuilder
StringBuilder builder = new StringBuilder(requestString);
// removing last character from String
builder.deleteCharAt(requestString.length() - 1);
How can a simple task be made complicated. My solution is:
public String removeLastChar(String s) {
return s[0..-1]
}
or
public String removeLastChar(String s) {
if (s.length() > 0) {
return s[0..-1]
}
return s
}
// Remove n last characters
// System.out.println(removeLast("Hello!!!333",3));
public String removeLast(String mes, int n) {
return mes != null && !mes.isEmpty() && mes.length()>n
? mes.substring(0, mes.length()-n): mes;
}
// Leave substring before character/string
// System.out.println(leaveBeforeChar("Hello!!!123", "1"));
public String leaveBeforeChar(String mes, String last) {
return mes != null && !mes.isEmpty() && mes.lastIndexOf(last)!=-1
? mes.substring(0, mes.lastIndexOf(last)): mes;
}
A one-liner answer (just a funny alternative - do not try this at home, and great answers already given):
public String removeLastChar(String s){return (s != null && s.length() != 0) ? s.substring(0, s.length() - 1): s;}
Most answers here forgot about surrogate pairs.
For instance, the character 𝕫 (codepoint U+1D56B) does not fit into a single char, so in order to be represented, it must form a surrogate pair of two chars.
If one simply applies the currently accepted answer (using str.substring(0, str.length() - 1), one splices the surrogate pair, leading to unexpected results.
One should also include a check whether the last character is a surrogate pair:
public static String removeLastChar(String str) {
Objects.requireNonNull(str, "The string should not be null");
if (str.isEmpty()) {
return str;
}
char lastChar = str.charAt(str.length() - 1);
int cut = Character.isSurrogate(lastChar) ? 2 : 1;
return str.substring(0, str.length() - cut);
}
Java 8
import java.util.Optional;
public class Test
{
public static void main(String[] args) throws InterruptedException
{
System.out.println(removeLastChar("test-abc"));
}
public static String removeLastChar(String s) {
return Optional.ofNullable(s)
.filter(str -> str.length() != 0)
.map(str -> str.substring(0, str.length() - 1))
.orElse(s);
}
}
Output : test-ab
public String removeLastCharacter(String str){
String result = null;
if ((str != null) && (str.length() > 0)) {
return str.substring(0, str.length() - 1);
}
else{
return "";
}
}
if we want to remove file extension of the given file,
** Sample code
public static String removeNCharactersFromLast(String str,int n){
if (str != null && (str.length() > 0)) {
return str.substring(0, str.length() - n);
}
return "";
}
For kotlin check out
string.dropLast(1)
if you have special character like ; in json just use String.replace(";", "") otherwise you must rewrite all character in string minus the last.
Why not use the escape sequence ... !
System.out.println(str + '\b');
Life is much easier now . XD ! ~ A readable one-liner
How to make the char in the recursion at the end:
public static String removeChar(String word, char charToRemove)
{
String char_toremove=Character.toString(charToRemove);
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == charToRemove)
{
String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord,charToRemove);
}
}
System.out.println(word);
return word;
}
for exemple:
removeChar ("hello world, let's go!",'l') → "heo word, et's go!llll"
removeChar("you should not go",'o') → "yu shuld nt goooo"
Here's an answer that works with codepoints outside of the Basic Multilingual Plane (Java 8+).
Using streams:
public String method(String str) {
return str.codePoints()
.limit(str.codePoints().count() - 1)
.mapToObj(i->new String(Character.toChars(i)))
.collect(Collectors.joining());
}
More efficient maybe:
public String method(String str) {
return str.isEmpty()? "": str.substring(0, str.length() - Character.charCount(str.codePointBefore(str.length())));
}
just replace the condition of "if" like this:
if(a.substring(a.length()-1).equals("x"))'
this will do the trick for you.
Suppose total length of my string=24
I want to cut last character after position 14 to end, mean I want starting 14 to be there.
So I apply following solution.
String date = "2019-07-31T22:00:00.000Z";
String result = date.substring(0, date.length() - 14);
I had to write code for a similar problem. One way that I was able to solve it used a recursive method of coding.
static String removeChar(String word, char charToRemove)
{
for(int i = 0; i < word.lenght(); i++)
{
if(word.charAt(i) == charToRemove)
{
String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord, charToRemove);
}
}
return word;
}
Most of the code I've seen on this topic doesn't use recursion so hopefully I can help you or someone who has the same problem.