I need to delete the set substring from string in Java. How I can to do it?
example:
string st1="The end of the text";
string st2="end of the ";
result:
st1="The text".
You can do this:
String newString = st1.replace(st2, "");
// String newString2 = st1.replaceAll(st2, ""); Alternative
// String newString3 = st1.replaceFirst(st2, ""); Alternative 2
However, your question smell homework so you should add that tag on future questions if this is true.
Java String documentation
Does the following do what you are looking for?
str1 = st1.replace(st2,"");
If you want to use substring(), you can do it like this:
public static String getCustomString(String s1, String s2)
{
if(s1.length() >= s2.length())
{
if(s1.contains(s2))
return s1.substring(0, s1.indexOf(s2)) + s1.substring(s1.indexOf(s2) + s2.length());
}
else
{
if(s2.contains(s1))
return s2.substring(0, s2.indexOf(s1)) + s2.substring(s2.indexOf(s1) + s1.length());
}
return "";
}
If homework (with minimal usage of Java API calls:
public void subString(String st1, String st2) {
int s2len = st2.length();
int s1len = st1.length();
int i = 0;
int count = 0;
while(i <= st1.length() && i+st2.length() <= st1.length()) {
if (st1.substring(i, i+st2.length()).equalsIgnoreCase(st2)) {
st1 = (i > 0? st1.substring(0, i) : "") + st1.substring(i+st2.length());
i=0;
}
else {
i++;
}
}
System.out.println(st1);
}
Otherwise:
st1.replace(st2, "");
Related
public static void perm(String str) {
perm1(str,"");
}
private static void perm1(String str, String prefix) {
int n = str.length();
if (n == 0) StdOut.println(prefix);
else {
for (int i = 0; i < n; i++){
String rem = str.substring(0,i) + str.substring(i+1);
perm1(rem, prefix + str.charAt(i));
}
}
}
If for example our case is "abc" .. where in the code does this string's length decrease so that we will eventually hit the base case ? I see we are always letting the rem as it is "abc" .. what am I missing ?
The point is that substring(int beginIndex, int endIndex) methods takes substring exclusively for endIndex. So for example for i = 1 you will get:
String str = "abc";
String s1 = str.substring(0, 1); // a
String s2 = str.substring(1 + 1); // c
String rem = s1 + s2; // ac
This is something I have been trying to do since morning but no luck so far.
Without the use of "regex" or replace() of String, but only loop, write a method that replaces occurance of string from parentString with something else.
I was able to implement a version where type char replaceWith is to be replaced, but no luck if a type String replaceWith is to be replaced as in the template below.
public String replaceWith(String parentString, String occurrence, String replaceWith){
String newString; //Initialize
//loop through "parentString",
//find and replace "occurence" with "replaceWith"
return newString;
}
Use a string searching algorithm, that checks the characters of the occurrence against all the characters up to the length of occurrence. Something like this Rabin-Karp Algorithm
function NaiveSearch(string s[1..n], string pattern[1..m])
for i from 1 to n-m+1
for j from 1 to m
if s[i+j-1] ≠ pattern[j]
jump to next iteration of outer loop
return i
return not found
Something like that:
public String replace(String source, String target, String replacement) {
int targetLength = target.length();
int sourceLength = source.length();
if (sourceLength < targetLength) {
return source;
}
String result = source;
for (int i = 0; i< sourceLength - targetLength; i++) {
String before = result.substring(0, i);
String substring = result.substring(i, i+targetLength - 1);
String after = result.substring(i + targetLength);
if (substring.equals(target)) {
result = before.concat(replacement).concat(after);
}
}
return result;
}
My quick solution was this. No guarantees all output is correct.
public static String replaceWith(String s, String find, String replace) {
StringBuilder sb = new StringBuilder();
int findLength = find.length();
int sourceLength = s.length();
for (int i = 0; i < sourceLength; i++) {
String nextSubstring;
if (i + findLength >= sourceLength) {
nextSubstring = s.substring(i);
} else {
nextSubstring = s.substring(i, i + findLength);
}
if (nextSubstring.equals(find)) {
sb.append(replace);
i += findLength - 1;
} else {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
Sample test
replaceWith("Hello World", "Hello", "World") => "World World"
replaceWith("HelloHelloWorld", "Hello", "World") => "WorldWorldWorld"
replaceWith("I replace banana, banana and some more banana", "banana", "apple") => I replace apple, apple and some more apple
I wrote this fast solution:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static String replaceWith(String parentString, String occurrence, String replaceWith){
String newString = "";
for(int i = 0; i <= parentString.length()-occurrence.length(); ++i) {
boolean add = false;
for(int j = 0; j < occurrence.length(); ++j) {
if(parentString.charAt(i+j) != occurrence.charAt(j)) add = true;
}
if(add) {
newString += parentString.charAt(i);
} else {
i += occurrence.length()-1;
newString += replaceWith;
}
}
return newString;
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(replaceWith("I replace banana, banana and some more banana", "banana", "apple"));
}
}
You can see this working here: https://ideone.com/GwB7Ba
It outputs:
I replace apple, apple and some more apple
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);
}
}
}
Is it possible to reverse String in Java without using any of the temporary variables like String, Char[] or StringBuilder?
Only can use int, or int[].
String reverseMe = "reverse me!";
for (int i = 0; i < reverseMe.length(); i++) {
reverseMe = reverseMe.substring(1, reverseMe.length() - i)
+ reverseMe.substring(0, 1)
+ reverseMe.substring(reverseMe.length() - i, reverseMe.length());
}
System.out.println(reverseMe);
Output:
!em esrever
Just for the fun of it, of course using StringBuffer would be better, here I'm creating new Strings for each Iteration, the only difference is that I'm not introducing a new reference, and I've only an int counter.
The objects of the Java String class are immutable - their contents cannot be altered after being created.
You will need at least two temporary objects - one for the final result and one for the intermediate values - even if you do find a way to avoid using a local variable.
EDIT:
That said, since you can use int[] you may be able to cheat.
Since char can be assigned to int, you can use String.charAt() to create an int array with the character values in reverse order. Or you may be allowed to use String.toCharArray() to get a char array that will be copied over to your int[] temporary.
Then you use the variable that holds the reference to your original string (or the result variable, if you are allowed one) to start from an empty string (easily obtainable with a direct assignment or String.substring()) and use String.concat() to create the final result.
In no case, however, will you be able to swap the characters in-place as you would do in C/C++.
EDIT 2:
Here's my version which does not use StringBuffer/Builders internally:
int r[] = new int[s.length()];
int idx = r.length - 1;
for (int i : s.toCharArray()) {
r[idx--] = i;
}
s = s.substring(0, 0);
for (int i : r) {
s = s.concat(String.valueOf((char)i));
}
String s = "Hello World!";
for(int i = 0; i < s.length(); i++)
{
s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
}
System.out.println(s); // !dlroW olleH
No temporary variables! :)
One of many ways:
String str = "The quick brown fox jumps over the lazy dog";
int len = str.length();
for (int i = (len-1); i >= 0; --i)
str += str.charAt(i);
str = str.substring(len);
System.out.println(str);
public String reverseStr(String str) {
if (str.length() <= 1) {
return str;
}
return reverseStr(str.substring(1)) + str.charAt(0);
}
Because you can use an int, you can assign an int a char value:
String aString = "abc";
int intChar = aString.charAt(0);
You will have to convert from the int back to the char to assign it to aString.charAt(2).
I'm sure you can figure it out from there.
First append the string to itself in reverse manner. Then take the second half out of it.
public class RevString {
public static void main(String[] args) {
String s="string";
for(int i=s.length()-1;i>=0;i--){
s+=s.charAt(i);
}
s=s.substring(s.length()/2, s.length());
System.out.println(s);
}
}
Without using any collection,StringBulider, StringBuffer or temp array reverse the string. Simple and crisp:
public static void main(String[] args) {
String test = "Hello World";
String rev = "";
Pattern p = Pattern.compile("[\\w|\\W]");
Matcher m = p.matcher(test);
while (m.find()) {
rev = m.group()+rev;
}
System.out.println("Reverse==" + rev);
}
Output
Reverse==dlroW olleH
Hope it helps :)
public class Test {
static St`enter code here`ring reverseString(String str) {
for (int i = 0; i < str.length() / 2; i++) {
if (i == 0) {
str = str.charAt(str.length() - 1 - i) + str.substring(i + 1, str.length() - 1 - i) + str.charAt(i);
} else {
str = str.substring(0, i) + str.charAt(str.length() - 1 - i)
+ str.substring(i + 1, str.length() - 1 - i) + str.charAt(i)
+ str.substring(str.length() - i, str.length());
}
}
return str;
}
public static void main(String args[]) {
String s = "ABCDE";
System.out.println(Test.reverseString(s));
}
}
String str = "Welcome";
for(int i=0;i<str.length();){
System.out.print(str.charAt(str.length()-1));
str = str.substring(0,str.length()-1);
}
Except for loop variables.
You can use class java.lang.StringBuilder:
String reservedString = new StringBuilder(str).reserve().toString();
String Y="part1 part2 part3",X="part1";
boolean foundMatch = false;
while(!foundMatch) {
foundMatch = Y.equals(X);
if(foundMatch) {
break;
}
else {
Y = useSplitToRemoveLastPart(Y);
if(Y.equals("")) {
break;
}
}
//implementation of useSplitToRemoveLastPart()
private static String useSplitToRemoveLastPart(String y) {
//What goes here .. It should chop the last part of the string..
return null;
}
Can anyone help ...
If you want part3 to be removed and provided that all the words are separated by space
String str ="part1 part2 part3";
String result = str.substring(0,str.lastIndexOf(" "));
If you really want to use split:
private static String useSplitToRemoveLastPart(String str) {
String[] arr = str.split(" ");
String result = "";
if (arr.length > 0) {
result = str.substring(0, str.lastIndexOf(" " + arr[arr.length-1]));
}
return result;
}
Your whole code can be optimized to:
boolean foundmatch = y.startsWith(x);
y = foundmatch? x : "";
public String removeLastSubstring(String target, String toRemove){
int idx = target.lastIndexOf(toRemove);
target = target.substring(0, idx) + target.substring(idx + toRemove.length());
return target;
}
You only need to pass it your target and the LAST substring you want to remove, example:
String s = "123 #abc# 456";
s = removeLastSubstring(s, "#abc#");
If you want to do it using split, then you can do:
String s[] = Y.split(" ");
String n = "";
for (int i = 0; i < s.length - 1; i++)
n+= s[i];
return n;
By the way, If the method you need to build is called useSplitToRemoveLastPart(String t), then I'd suggest you to use split to remove last part.
Take a look here.