Need advice on the usage of .indexOf(); [closed] - java

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()

Related

Check Permutation of string in Java [closed]

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?

Blank space in array with String splitter [closed]

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.

How can I read this string in Java? [closed]

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 string such as this: "xxxxxxx , yyyyyyy - zzzzzz"
and sometimes it happens to be "xxxxxxx - zzzzzz"
the length of x may vary.
What I want to get, is always the x word.
Is there an easy way to do this?
What I thought was:
Iterate through the string, append to a stringbuilder every char I read until I read a ",", then break the iteration and I get the word, but this looks pretty messy.
So maybe there is an easier way to do this.
Here are several ways to get the first character:
String str = "x , y - zzzzzz";
System.out.println(str.charAt(0));
System.out.println(str.substring(0, 1));
System.out.println(str.replaceAll("^(.).*", "$1"));
See IDEONE demo
Choose the one you like more :)
UPDATE:
To find the first word, you may use the following regex pattern:
String pattern = "[\\s\\p{P}]+";
\s stands for whitespace, and \p{P} stands for punctuation.
You can use split with this as in
String str = "xxxxxxx , yyyyyyy - zzzzzz";
System.out.println(str.split(pattern)[0]);
str = "xxxxxxx - zzzzzz";
System.out.println(str.split(pattern)[0]);
str = "xxxxxxx, zzzzzz";
System.out.println(str.split(pattern)[0]);
str = "xxxxxxx-zzzzzz";
System.out.println(str.split(pattern)[0]);
All will output xxxxxxx. However, if you need to restrict the punctuation to some smaller subset, either exclude them in the &&[^-] negated subtraction:
[\\s\\p{P}&&[^-]]+
Or just define your own range:
[\\s.,;:]+
Just another demo

How to check if a string consists of 2 integers with a blank space in-between [closed]

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

Java: Splitting a String at two different points into 3 parts [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
First post. Be nice?
Learning Java.
I have a String object "1 Book on wombats at 12.99"
I want to split this String into either a String[] OR an ArrayList<String> splitting the string on the first space and around the word " at " so my String[] has 3 Strings of "1" "Book on wombats" "12.99"
my current solution is:
// private method call from my constructor method
ArrayList<String> fields = extractFields(item);
// private method
private ArrayList<String> extractFields (String item) {
ArrayList<String> parts = new ArrayList<String>();
String[] sliceQuanity = item.split(" ", 2);
parts.add(sliceQuanity[0]);
String[] slicePrice = sliceQuanity[1].split(" at ");
parts.add(slicePrice[0]);
parts.add(slicePrice[1]);
return parts;
}
So this works fine, but surely there is a more elegant way? perhaps with regex which is something that I'm still trying to get a good handle on.
Thankyou!
your could use this pattern
^(\S+)\s(.*?)\sat\s(.*)$
Demo
^ begining of string
(\S+) caputre anything that is not a white space
\s a white space
(.*?) capture as few as possible
\sat\s followed by a white space, the word "at" and a white space
(.*)$ then capture anything to the end
This regex will return what you need: ^(\S+)\s(.*?)\sat\s(.*)$
Explanation:
^ assert position at start of a line.
\S+ will match any non-white space character.
\s will match any white space character.
.*? will match any character (except newline).
\s again will match any white space character.
at matches the characters at literally (case sensitive).
\s again will match any white space character.
(.*)$ will match any character (except newline), and assert position at end of a line.
Well it would be simpler by just calling .split() on item.
Store that array in a String[], then hardcode which index you want of your String[] into the ArrayList that you are returning. The String.concat() method might help as well.
Here's a piece of code to arrive at the String[] result that you requested. Using the regex expression suggested in the other answers:
^(\S+)\s(.*?)\sat\s(.*)$ is converted to a Java string by escaping each of the backslashes with another backslash, so they appear twice when creating the Pattern object.
String item = "1 Book on wombats at 12.99";
Pattern pattern = Pattern.compile("^(\\S+)\\s(.*?)\\sat\\s(.*)$");
Matcher matcher = pattern.matcher(item);
matcher.find();
String[] parts = new String[]{matcher.group(1),matcher.group(2),matcher.group(3)};

Categories