Remove duplicate string in java - java

I have two different string, let's say:
s1 = "hello"
s2 = "helloworlde1"
I want to get result as worlde1.
Can anybody suggest me how to achieve this?

try this
s2=s2.replace(s1,"");
this will remove s1 from s2

Hope below small example will help you.
public class Test {
public static void main(String a[])
{
String s1="hello";
String s2="helloworlde1";
s2=s2.replace(s1, "");
System.out.println(s2);
}
}

If we assume that the duplicate string is always going to be in front of the other string e.g
s2="helloworlde1"
then you can use Java "substring" like this
string output = s2.substring(s1.length())
otherwise you need some other logic to locate where the duplicated string is before using the substring method

Related

alternate method for using substring on a String

I have a string which contains an underscore as shown below:
123445_Lisick
I want to remove all the characters from the String after the underscore. I have tried the code below, it's working, but is there any other way to do this, as I need to put this logic inside a for loop to extract elements from an ArrayList.
public class Test {
public static void main(String args[]) throws Exception {
String str = "123445_Lisick";
int a = str.indexOf("_");
String modfiedstr = str.substring(0, a);
System.out.println(modfiedstr);
}
}
Another way is to use the split method.
String str = "123445_Lisick";
String[] parts = string.split("_");
String modfiedstr = parts[0];
I don't think that really buys you anything though. There's really nothing wrong with the method you're using.
Your method is fine. Though not explicitly stated in the API documentation, I feel it's safe to assume that indexOf(char) will run in O(n) time. Since your string is unordered and you don't know the location of the underscore apriori, you cannot avoid this linear search time. Once you have completed the search, extraction of the substring will be needed for future processing. It's generally safe to assume the for simple operations like this in a language which is reasonably well refined the library functions will have been optimized.
Note however, that you are making an implicit assumption that
an underscore will exist within the String
if there are more than one underscore in the string, all but the first should be included in the output
If either of these assumptions will not always hold, you will need to make adjustments to handle those situations. In either case, you should at least defensively check for a -1 returned from indexAt(char) indicating that '_' is not in the string. Assuming in this situation the entire String is desired, you could use something like this:
public static String stringAfter(String source, char delim) {
if(source == null) return null;
int index = source.indexOf(delim);
return (index >= 0)?source.substring(index):source;
}
You could also use something like that:
public class Main {
public static void main(String[] args) {
String str = "123445_Lisick";
Pattern pattern = Pattern.compile("^([^_]*).*");
Matcher matcher = pattern.matcher(str);
String modfiedstr = null;
if (matcher.find()) {
modfiedstr = matcher.group(1);
}
System.out.println(modfiedstr);
}
}
The regex groups a pattern from the start of the input string until a character that is not _ is found.
However as #Bill the lizard wrote, i don't think that there is anything wrong with the method you do it now. I would do it the same way you did it.

How to check if a string equals to "}"

How to check if a string is equals to "}"?
I've tried
str_.equals("\\}");
and
str_.equals("[}]");
None of them seems working.
Use String#equals like that:
str_.equals("}");
Just do str_.equals("{");
or str_.equals("}");
We are still not sure which brace
EDIT: Ah now we have clarity.
Use str_.equals("}");
public static void main(String[] args) {
String s = "}";
System.out.println(s.equals("}"));
}
StringName.equals("}");
if you want to ckeck whether some string contain '{' use
StringName.contains("}");
EDIT : If you used
str_.equals("}"); before. may be your string contains white spaces.
to avoid that do as follows
str_.trim().equals("}");
Now white spaces no longer an issue.
Try this simple Java - String equals() Method method buddy......
String val1="{", val2="}";
if(val1.equals("{"))
{
System.out.println("Open Brackets");
}
else if(val2.equals("}"))
{
System.out.println("Close Brackets");
}

Can I use the replaceFirst method to look for a string pattern and replace it?

I have a question involving the Replace Method. I saw a question similar to this on here, but I tried to do the replaceFirst but it didn't work for me. Is there, any way I can use the replace method to change a string that results in: Helle, Werld; to get it to result to BE "Hello, World" using the replace method. Is there a way using the replaceFirst method for me to search for the sequence of "le" and replace it with "lo" and also change "We" to "Wo"?. Please see my code below:
public class Printer
{
/**Description: Replacement class
*
*
*/
public static void main(String[] args)
{
String test1Expected = "Hello, World!";
String newString1;
String test1 = "Holle, Werld!";
newString1 = test1.replace('o', 'e');
//Could I do: newString1.replaceFirst("le","lo);
System.out.println("newString1 = " + newString1);
//Output comes out to "Helle, Werld!"
}
}
You can do two regular expressions separatelt one after the other. Please try the following
newString1 = newString1.replaceAll("le", "lo").replaceAll("We", "Wo");

Output urls containing some words from a string to another string java

I have a string containing several urls. I want to retrieve the urls containing "thistext" and copy them into another variable named "outputlinks". This is my code.
String links = "http://www.website1.com/thistext
http://www.website1.com/othertext
http://www.website1.com/thistext";
String outputlinks =""; // ??
Assuming you meant:
String links = "http://www.website1.com/thistext\n" +
"http://www.website1.com/othertext\n" +
"http://www.website1.com/thistext";
Then you can do:
public static void main(String[] args) {
String links = "http://www.website1.com/thistext\n" +
"http://www.website1.com/othertext\n" +
"http://www.website1.com/thistext";
String[] linksArray = links.split("\n");
for (String link : linksArray) {
if (link.contains("thistext")) {
System.out.println(link);
}
}
}
First of all use a good separator for your links, like commah, semi colon or something else. Use a string tokenizer to get the individual links and finally search for your term, i.e "thisText" in each of the tokenized strings, using indexOf. That will get the job done for you.

Insert string in beginning of another string

How to insert a string enclosed with double quotes in the beginning of the StringBuilder and String?
Eg:
StringBuilder _sb = new StringBuilder("Sam");
I need to insert the string "Hello" to the beginning of "Sam" and O/p is "Hello Sam".
String _s = "Jam";
I need to insert the string "Hello" to the beginning of "Jam" and O/p is "Hello Jam".
How to achieve this?
The first case is done using the insert() method:
_sb.insert(0, "Hello ");
The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:
String s2 = "Hello " + _s;
Other answers explain how to insert a string at the beginning of another String or StringBuilder (or StringBuffer).
However, strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable1.
When you write:
String s = "Jam";
s = "Hello " + s;
you are actually causing a new String object to be created that is the concatenation of "Hello " and "Jam". You are not actually inserting characters into an existing String object at all.
1 - It is technically possible to use reflection to break abstraction on String objects and mutate them ... even though they are immutable by design. But it is a really bad idea to do this. Unless you know that a String object was created explicitly via new String(...) it could be shared, or it could share internal state with other String objects. Finally, the JVM spec clearly states that the behavior of code that uses reflection to change a final is undefined. Mutation of String objects is dangerous.
Sure, use StringBuilder.insert():
_sb.insert(0, _s);
You can add a string at the front of an already existing one. for example, if I have a name string name, I can add another string name2 by using:
name = name2 + name;
Don't know if this is helpful or not, but it works. No need to use a string builder.
private static void appendZeroAtStart() {
String strObj = "11";
int maxLegth = 5;
StringBuilder sb = new StringBuilder(strObj);
if (sb.length() <= maxLegth) {
while (sb.length() < maxLegth) {
sb.insert(0, '0');
}
} else {
System.out.println("error");
}
System.out.println("result: " + sb);
}
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Create a new StringBuilder.
StringBuilder builder = new StringBuilder();
// Loop and append values.
for (int i = 0; i < 5; i++) {
builder.append("abc ");
}
// Convert to string.
String result = builder.toString();
// Print result.
System.out.println(result);
}
}
It is better if you find quotation marks by using the indexof() method and then add a string behind that index.
string s="hai";
int s=s.indexof(""");

Categories