Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
The Question I have is :
For a given two strings, 'str1' and 'str2', check whether they are a permutation of each other or not.
Permutations of each other
Two strings are said to be a permutation of each other when either of the string's characters can be rearranged so that it becomes identical to the other one.
Example:
str1= "sinrtg"
str2 = "string"
The character of the first string(str1) can be rearranged to form str2 and hence we can say that the given strings are a permutation of each other.
Input Format:
The first line of input contains a string without any leading and trailing spaces, representing the first string 'str1'.
The second line of input contains a string without any leading and trailing spaces, representing the second string 'str2'.
Note:
All the characters in the input strings would be in lower case.
Output Format:
The only line of output prints either 'true' or 'false', denoting whether the two strings are a permutation of each other or not.
You are not required to print anything. It has already been taken care of. Just implement the function.
My code for this:
public static boolean isPermutation(String str1, String str2) {
//Your code goes here
boolean ans=false;
if (str1.length()==str2.length()){
for (int i=0;i<str1.length();i++){
ans=false;
for (int j=0;j<str2.length();j++){
if (str1.charAt(i)==str2.charAt(j)){
ans=true;}
}
if (ans == false){
break;}
}
}else{
return false;
}
return ans;
}
One test case is giving me a wrong answer . Cany anybody help which test case will this code not work for ?
Your code checks two things:
That str1 and str2 have the same length.
For each character in str1, that this character exists in str2.
This does not work, as you found out.
A trivial example is:
str1 = "hello"
str2 = "ehhlo"
Note how these are not permutations: str2 has 2 h characters and only one l. However, they have the same length, and str2 contains every character in str1.
One convoluted solution is to not just scan for the target letter, but also remove it (use it up). This would be easier if you pile all characters in a list first.
However, there is a vastly simpler way to do all this, and to make the algorithm considerably faster to boot. As this is clearly homework, and not the direct question you asked, I'll simply give you a hint: Is there a thing you can do to both str1 and str2 such that, once that's been done, the question can be answered simply by checking if str1 and str2 are equal?
Related
This question already has answers here:
How to remove duplicate white spaces in string using Java?
(9 answers)
Closed 6 years ago.
A String can contain multiple spaces in a row - I need to replace multiple subsequent spaces by one single space char. The "problem" is that i cant know how many spaces there may encounter. The function I look for shall not only replace the first occurance of a found match, but all multiple equal characters in a String.
I searched a lot on the internet and tried the regex "X*? (X, zero or more times)" which I found unter "Reluctant quantifiers" on https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#sum
That didnt work: s1 = s1.replaceAll(" *?", " ");
Where s1 = "Hello World"; should be converted to s1 = "Hello World";
I'd be thankful for any help.
You can use replaceAll() that replaces whitespaces with just a single space.
String st = "helllo world"
System.out.println(st.replaceAll("\\s+"," "))
Output : helllo world
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a regex question assigned by my instructor and he wants us to make all the return values true by changing the string value in the three declared variables. This is my first time doing a regex question and I wanted a little help if that's okay. I tried www.regexpal.com but I didn't know how to use it.
Could someone shed a little light on this topic as to how I begin to solve this? Thanks
Heres the following code:
public class RegexTester {
public static void main(String[] args) {
String regexSSN = ""; //TODO add a regex for Social Security Numbers
String regex9000 = ""; //TODO add a regex for GGC 9000 numbers here
String regexZipPlus4 = ""; //TODO add a regex for zip+4 zipcodes here
System.out.println("All of the following tests shoule return true, "
+ "the negative tests are negated (meaning that they should "
+ "also return true)");
System.out.println("192-192-5555".matches(regexSSN)); // the following tests should all match
System.out.println("444-183-1212".matches(regexSSN));
System.out.println("032-431-9375".matches(regexSSN));
System.out.println("122-650-4343".matches(regexSSN));
System.out.println("900012389".matches(regex9000));
System.out.println("900112389".matches(regex9000));
System.out.println("900012390".matches(regex9000));
System.out.println("900050000".matches(regex9000));
System.out.println("30043".matches(regexZipPlus4));
System.out.println("30043-1234".matches(regexZipPlus4));
System.out.println(); // the following codes print out true
System.out.println(!"192-XYZ-5555".matches(regexSSN)); // the following tests should NOT match
System.out.println(!"00-192-5555".matches(regexSSN));
System.out.println(!"90005000".matches(regex9000)); // too short!
System.out.println(!"900250000".matches(regex9000)); // must be 9000* or 9001*
System.out.println(!"9002500001".matches(regex9000)); // to big
System.out.println(!"9001FOO00".matches(regex9000)); // no alpha allowed
System.out.println(!"30043-12345".matches(regexZipPlus4)); // too long
System.out.println(!"300430-1234".matches(regexZipPlus4)); // too long
System.out.println(!"30043-12".matches(regexZipPlus4)); // too short
System.out.println(!"300FO-1234".matches(regexZipPlus4)); // no alpha allowed
System.out.println(!"30043=1234".matches(regexZipPlus4)); // missing hyphen
}
}
Start with reading through java.util.regex.Pattern documentation. It contains all necessary information to complete the assignment. You need to clearly understand requirements when constructing your regex pattern. You can then convert those requirements into regex.
E.g., to match telephone number of the following format XXX-XXX-XXXX, where X is any number you need
3 digits followed by dash, followed by 3 digits, followed by another dash and then by 4 digits:
$\d{3}\-\d{3}\-\d{4}$
Please note that when assigning this pattern to a Java string, you need to escape special characters.
I like using RegexPlanet to test my code. Here is a link for the fist problem: regexSSN (although ssn should be 9 digit long, in your code it's 10). Click on Go button. You will be able to enter your test cases.
Here's the solution for your fist case.
String regexSSN = "^(\\d{3}\\-\\d{3}\\-\\d{4})";
Hopefully this will get you started so you can complete other two problems.
When designing regex strings, I like to begin by categorizing parts of the string into similar components. Lets take the SSN regex as an example.
Step 1: We see the format is ###-###-##### where # is a number 0-9
Step 2: The regex for matching a number is either [0-9] or \d
Step 3: Now we can write it out in regex \d\d\d-\d\d\d-\d\d\d\d where - is just a literal dash.
Step 4: Notice repetition? We can take care of that too with {n} where n is the number of time we want to repeat the previous section, so now we have \d{3}-\d{3}-\d{4}
And thats how you do SSN Regex.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My objective is to separate the numbers from the string, but in my array's first position i get a blank space. So i need help for that not to happen.
str1 = "Y=9x1+29x2";
String[] split2 = str2.split("[^-?.?0-9]+");
Blank space at the start is due to presence of non-digit character at the start of your input.
You can remove all non-digits at start before splitting:
String linha = "Y=9x1+29x2";
String[] split = linha.replaceFirst("[^-.\\d]+", "").split("[^-.\\d]+");
for (String tok: split2)
System.out.println(tok);
Output:
9
1
29
2
I think your question is rather vague, but after looking at it, I'm guessing that you want to extract the numbers out of the string, where a "number" has this format: an optional minus sign, followed by an optional decimal point, followed by one or more digits. I suspect you also want to include numbers that have digits followed by a decimal point followed by more digits.
I'm guessing this is what you want, because of the ? you put in your regex. The problem is that inside square brackets, ? doesn't mean "optional", and it doesn't mean "zero or one of something". It means a question mark. The regex [^-?.?0-9] means "match one character that is not a digit, a period, a hyphen, or a question mark". A pattern in square brackets always matches one character, and you tell it what characters are OK (or, if you begin with ^, what characters are not OK). This kind of "character set" pattern never matches a sequence of characters. It just looks at one character at a time. If you put + after the pattern, it still looks at one character at a time; it just does so repeatedly.
I think what you're trying to do is to take a pattern that represents a number, and then say "look for something that doesn't look like that pattern", and you tried to do it by using [^...]. That simply will not work.
In fact, split() is the wrong tool for this job. The purpose of split is to break up a string whose delimiters match a given pattern. Using it when the strings you want to keep in the array match a given pattern doesn't work very well, unless the pattern is extremely simple. I recommend that you create a Matcher and use the find() method in a loop. find() is set up so that it can find all matching substrings of a string if you call it repeatedly. This is what you want to accomplish, so it's the right tool.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
As the title states, i want to know how i can check if a string consists of 2 integers with a blank space in between them in Java.
As an example:
0 2, should return true.
0 abc, should return false.
abcsd, should return false.
And so on...
If it is to any help, I am getting my string from a text file with a buffered reader. Maybe there is a more direct and easier way?
Thank you in advance
You could use string.matches method.
string.matches("\\d+\\s\\d+");
DEMO
\d+ matches one or more digits. So this asserts that the input string must contain a number at the start.
\s matches a space character. So this asserts that the input string must contain a space at the middle.
\d+ matches one or more digits. So this asserts that the input string must contain a number at the end.
Since matches method tries to match the whole input string, you don't need to add start and end anchors to your regex.
Because you haven't posted your own code here, I assume that you haven't made much research into it, have you? First of all, will you use only 1-digit numbers? Here's how you should start: http://docs.oracle.com/javase/tutorial/java/data/converting.html
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have some code:
firstWord = sentance.substring (0, sentance.indexOf(' '));
secondWord = sentance.substring(sentance.indexOf(' ') + 1);
the code is used for selecting the first word out of a string without the use of arrays.
However I am wondering if I can further fool-proof my code by implementing a safeguard so that if the user inputs two spaces, the code will take the group of white space and count it as one unit.
Is this possible without the use of arrays, or loops?
For example the user would input this:
"Hello 2spaces there"
the user accidentally inputted two spaces in the beginning which will mess the program up when it tries to take the second word i think.
remove multiple space with single space as :
String str="Hello world this is string";
str=str.replaceAll("\\s+", " ");
.......// do whatever you want
Your code will not take the first word out of string only if the first character of the string is a space, or before the first space is not a word, or there is no space, for example " hello" -> "", "!##! blah" -> "!##!", "asdasd" -> ""
y.indexOf(x) returns the index of the first occurrence of x in y.
Your solution is mostly foolproof, but it will fail to get the first word if there are spaces before it, or there is no whitespace in the specified string, because indexOf would return -1.
You should call the .trim() method on the string object you want to get the first word of, it will remove the whitespace around the string, and then add a single space character at the end of the string.
str = "Hello I'm your String";
String[] splited = str.split("\\s+");
You can use arrays they are not that bad.
If you really must avoid using an array, you could use sentance.replaceAll("\\s+", " "); first to collapse all sequences of consecutive whitespace into singleton spaces.
(Similarly, you would want to trim() leading and trailing whitespace as well.)
If you just want to remove trailing and leading whitespace use .trim()
str = str.trim()