Skip to content
Advertisement

Tag: string

Calling equals on string literal

I just was tidying my code a bit and there was this piece: Then I thought of doing it the other way around to get rid of the checking for null: It definitely works, but is this safe to do so? I mean string literals are stored in a common pool, while string object create by new are on the

Delete anything between “<” and “>” in a String

I have try restString = restString.replaceAll(“\&lt;.*\&gt;”, “”); and restString = restString.replaceAll(“\&lt;[^(\&gt)]*\&gt;”, “”);. Both seems don’t work. I don’t know if I could represent the meaning in the regular expression. Answer Make your regex non-greedy: Also I used (?s) to make dot match newlines as well.

Finding second occurrence of a substring in a string in Java

We are given a string, say, “itiswhatitis” and a substring, say, “is”. I need to find the index of ‘i’ when the string “is” occurs a second time in the original string. String.indexOf(“is”) will return 2 in this case. I want the output to be 10 in this case. Answer Use overloaded version of indexOf(), which takes the starting index

Scanner needs/is requesting input twice

I’m just writing a small program that receives input from the user then prints it back to them. However, when I run the program it asks for input twice (it prints the initial statement, then once you type and press enter, nothing happens, but if you do it again it works and prints.) The top value apparently has no weight

How to sort an array of objects in Java?

My array does not contain any string. But its contains object references. Every object reference returns name, id, author and publisher by toString method. Now I need to sort that array of objects by the name. I know how to sort, but I do not know how to extract the name from the objects and sort them. Answer You have

Check and extract a number from a String in Java

I’m writing a program where the user enters a String in the following format: I need to check that there is a number in the String and then extract just the number. If i use .contains(“\d+”) or .contains(“[0-9]+”), the program can’t find a number in the String, no matter what the input is, but .matches(“\d+”)will only work when there is

Formatting a string array in java

I have a string array which has k elements. I want to print them out using System.out.format, but the issue is that I do not know k. So essentially, I want to use something like: System.out.format(“%s %s … k times”, str1, str2, … strk); (where k is a variable) I was looking through the java documentation, but could not find

Advertisement