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");
}
Related
I have been trying to figure out why this Java code won't delete any leading whitespace to my actual string, I have been trying to use stripLeading() method and the trim(); method, and various other methods with the same functionality but still haven't gotten a favorable outcome. Code:
public static String message(String logLine) {
logLine = (String) logLine.subSequence(logLine.indexOf(" ") + 1, logLine.length());
return logLine;
}
public static void main(String[] args) {
System.out.println(message("[WARNING]: \tTimezone not set \r\n"));
}
What results is what I wanted, just the words "Timezone not set" however I want this program to completely ignore leading whitespace, which for some reason it can't. Thank you for any help.
Possible solutions
Use String::replaceFirst to keep only the part after a prefix ([WARNING]:) followed by whitespaces and the main part:
public static String message(String logLine) {
return logLine.replaceFirst("^\\S*\\s+(\\S+(\\s+\\S+)*)\\s+$", "$1");
}
As the prefix ends with ':', a solution offered in the comment using String::substring + String::trim works too:
public static String message(String logLine) {
return logLine.substring(logLine.indexOf(":") + 1).trim();
}
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
I know there are a lot of questions and answers related to similar questions but I couldn't find an answer to my question. This a small snippet of my code:
private String substitute(String text) {
List<Macro> macros = getMacros();
for (Macro macro : macros) {
text = StringUtils.replace(text, macro.getKey(), macro.getValue());
}
return text;
}
Would this be a good way to substitute multiple macros variables in a text String? This creates a new String object on every loop so I am wondering if there's a better way to do this. Ideally I would have used Apache Commons StrSubstitutor class but I can't because of the format of the tokens/macros (different formats and not between a fixed prefix/suffix). I also don't want to use Regex because of performance issues.
According to some coding rules at work I need to mark the argument as final. I wonder if that's indeed good practice here. I know that Strings are immutable and I know that whenever I call StringUtils.replace() it will return me a new String object. But I am wondering if the String argument here should be marked as final as suggested and in the method do something like this:
String result = text;
for (Macro macro : macros) {
result = StringUtils.replace(result, macro.getKey(), macro.getValue());
}
I just don't like this.
Any help would be appreciated. Thanks.
You can use apache velocity to replace a string with keys with the equivalent string with values.
Your concern seems to be valid. String is immutable so it creates multiple objects. You should you either use StringBuilder or StringBuffer.
I wrote a sample for you. Build from here
private static String substitute(String text) {
List<Macro> macros = getMacros();
StringBuffer st = new StringBuffer(text);
for (Macro macro : macros) {
int start = st.indexOf(macro.getKey());
if (start != -1) {
st.replace(start, start + macro.getKey().length(), macro.getValue());
}
}
return st.toString();
}
Cheers!!
If you have some concerns about performance you could use a StringBuilder, which allows you to declare the text param as final:
private String substitute(final String text) {
List<Macro> macros = getMacros();
StringBuilder stringBuilder=new StringBuilder(text);
for(Macro macro: macros) {
int index=stringBuilder.indexOf(macro.getKey());
if (index!=-1) {
stringBuilder.replace(index, index+macro.getKey().length(), macro.getValue());
}
}
return stringBuilder.toString();
}
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.
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");