Java: Find a certain character and get substring - java

I have a string 4.9.14_05_29_16_21 and I need to get 4.9 only. The numbers vary so I can't simply get the first three elements of this char array. I have to find the right most . and substring it till there.
I'm from Python so I'll show Python approach to this.
def foobar(some_string):
location = some_string.rfind('.')
new_string = some_string[0:location]
return new_string
How would I do this in Java?

Use String#lastIndexOf and String#substring:
int location = someString.lastIndexOf('.');
String newString = someString.substring(0, location);
Also note that I've assumed Java's naming convention (i.e. camelCase). If there can be cases where the input does not include a period, you can check if location is negative and include logic to deal with that case.

You should use the following methods:
String.lastIndexOf(int ch) to get the index
String.substring(int beginindex, int endindex) to
extract the String.
Make sure to put an error check in if the string doesn't contain any ., i.e. lastIndexOf returns -1.
public String getBeforePeriod(String input) {
int index = input.lastIndexOf('.');
return index > -1 ? input.substring(0,index) : input;
}

Use String.indexOf() method to provide one second argument to substring() method.
Here is a link to more info.
http://www.tutorialspoint.com/java/java_string_indexof.htm

Related

finding the middle index of a substring when there are duplicates in the string

I was working on a Java coding problem and encountered the following issue.
Problem:
Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one
xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBBB") → false
My Code:
public boolean xyzMiddle(String str) {
boolean result=false;
if(str.length()<3)result=false;
if(str.length()==3 && str.equals("xyz"))result=true;
for(int j=0;j<str.length()-3;j++){
if(str.substring(j,j+3).equals("xyz")){
String rightSide=str.substring(j+3,str.length());
int rightLength=rightSide.length();
String leftSide=str.substring(0,j);
int leftLength=leftSide.length();
int diff=Math.abs(rightLength-leftLength);
if(diff>=0 && diff<=1)result=true;
else result=false;
}
}
return result;
}
Output I am getting:
Running for most of the test cases but failing for certain edge cases involving more than once occurence of "xyz" in the string
Example:
xyzMiddle("xyzxyzAxyzBxyzxyz")
My present method is taking the "xyz" starting at the index 0. I understood the problem. I want a solution where the condition is using only string manipulation functions.
NOTE: I need to solve this using string manipulations like substrings. I am not considering using list, stringbuffer/builder etc. Would appreciate answers which can build up on my code.
There is no need to loop at all, because you only want to check if xyz is in the middle.
The string is of the form
prefix + "xyz" + suffix
The content of the prefix and suffix is irrelevant; the only thing that matters is they differ in length by at most 1.
Depending on the length of the string (and assuming it is at least 3):
Prefix and suffix must have the same length if the (string's length - the length of xyz) is even. In this case:
int prefixLen = (str.length()-3)/2;
result = str.substring(prefixLen, prefixLen+3).equals("xyz");
Otherwise, prefix and suffix differ in length by 1. In this case:
int minPrefixLen = (str.length()-3)/2;
int maxPrefixLen = minPrefixLen+1;
result = str.substring(minPrefixLen, minPrefixLen+3).equals("xyz") || str.substring(maxPrefixLen, maxPrefixLen+3).equals("xyz");
In fact, you don't even need the substring here. You can do it with str.regionMatches instead, and avoid creating the substrings, e.g. for the first case:
result = str.regionMatches(prefixLen, "xyz", 0, 3);
Super easy solution:
Use Apache StringUtils to split the string.
Specifically, splitByWholeSeparatorPreserveAllTokens.
Think about the problem.
Specifically, if the token is in the middle of the string then there must be an even number of tokens returned by the split call (see step 1 above).
Zero counts as an even number here.
If the number of tokens is even, add the lengths of the first group (first half of the tokens) and compare it to the lengths of the second group.
Pay attention to details,
an empty token indicates an occurrence of the token itself.
You can count this as zero length, count as the length of the token, or count it as literally any number as long as you always count it as the same number.
if (lengthFirstHalf == lengthSecondHalf) token is in middle.
Managing your code, I left unchanged the cases str.lengt<3 and str.lengt==3.
Taking inspiration from #Andy's answer, I considered the pattern
prefix+'xyz'+suffix
and, while looking for matches I controlled also if they respect the rule IsMiddle, as you defined it. If a match that respect the rule is found, the loop breaks and return a success, else the loop continue.
public boolean xyzMiddle(String str) {
boolean result=false;
if(str.length()<3)
result=false;
else if(str.length()==3 && str.equals("xyz"))
result=true;
else{
int preLen=-1;
int sufLen=-2;
int k=0;
while(k<str.lenght){
if(str.indexOf('xyz',k)!=-1){
count++;
k=str.indexOf('xyz',k);
//check if match is in the middle
preLen=str.substring(0,k).lenght;
sufLen=str.substring(k+3,str.lenght-1).lenght;
if(preLen==sufLen || preLen==sufLen-1 || preLen==sufLen+1){
result=true;
k=str.length; //breaks the while loop
}
else
result=false;
}
else
k++;
}
}
return result;
}

str.find() equivalent in java?

Hi I'm trying to learn java so I'm converting my working c++ code to java. But I'm unsure about how to proceed with str.find(). Is there an equivalent of this in java? What I want to happen is I look for the first occurrence of a string in another string after the first comma not integer. I know of indexOf() and indexLastOf but they will only produce the fist and last occurrences.
void found() {
int count = 1;
size_t find = str.find(',');
while (find != string::npos) {
count++;
find = str.find(',', find + 1);
}
}
};
you can use str.indexOf('some string', indexToStartLooking); which will find the first occurrence of "some string" after the int in the second parameter and will return an int.
Try using Java's Pattern and Matcher. Those classes involve regex pattern matching. It is very easy. Search here for other existing posts on that subject.

Is it possible to find how many letters are used in a string?

I have a string and I want to use some formulas, in which there is a word that is going to be searched. Sometimes that word could be in different place, depending on the user. In order to make substrings work, I have to ensure that when it happens, the code still works.
String temp = s;//Temp is a long string text
String fehlerspeicher="fehlerspeicher";
if(temp.matches(".*"+fehlerspeicher+".*")){
// i have to find as an integer, how many LETTERS are used till this spesific word
}//to make changes in the following code
String temp1=temp.substring(0, 15000);//15000 is an example. it can be 5000 or 20000 sometimes. It splits the text up from 15000th letter.
String temp2=temp.substring(15000);// It'd be useful to use this integer in these 2 formulas.
temp2=temp2.replaceFirst("200", "20_");
temp=temp1+temp2;
So, could it be somehow implementable? Thanks.
Use indexOf:
public int indexOf(String str)
Returns the index within this string of the first occurrence of the
specified substring.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#indexOf(java.lang.String)
So to get the index of "fehlerspeicher" you can use:
int index = temp.indexOf("fehlerspeicher");
So to get the position of the 'f' in 'fehlerspeicher' you can use:
String temp = "hellofehlerspecher"; //example temp string
int index = temp.indexOf("fehlerspeicher");
int fPos = index + 1; //fpos will equal 6.

Checking more than one character with CharAt()

I am struggling with the charAt method.what i want to know is if when you use charAt, are you able to use more than one number in the parameter, so that you look at more than one character in one method?
No, there is no vanilla JavaScript method for that. You could always write one that prototypes the String object, though:
String.prototype.charsAt = function(indexes) {
var returned = [ ];
for(var i = 0; i < indexes.length; i++)
{
returned.push(this.charAt(indexes[i]));
}
return returned;
}
You can then call it using:
var text = 'mystring';
alert(text.charsAt([0, 1]));
You can see a working demo here > http://jsfiddle.net/MDNRS/. As others have said though, this is really entirely trivial, as you should use substr() or other methods.
From javadoc:
charAt
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() -
The first char value of the sequence is at
index 0, the next at index 1, and so on, as for array indexing.
If you need something else you can use toCharArray() to access the underlying char[] and do what you need
looks like your understanding of method charat(int index) is a little bit off. Calling this method is simply to get a single character at specified index.
If you are looking for searching a specific character sequence, you might want to look into the contains(CharSequence cs) method of String class.
Reference:
Java API

How to search the whole string for a specific word?

I have this code which searches a string array and returns the result if the input string matches the 1st characters of a string:
for (int i = 0; i < countryCode.length; i++) {
if (textlength <= countryCode[i].length()) {
if (etsearch
.getText()
.toString()
.equalsIgnoreCase(
(String) countryCode[i].subSequence(0,
textlength))) {
text_sort.add(countryCode[i]);
image_sort.add(flag[i]);
condition_sort.add(condition[i]);
}
}
}
But i want to get those string also where the input string matches not only in the first characters but also any where in the string? How to do this?
You have three way to search if an string contain substring or not:
String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0; // true if contains
// Anywhere in string
b = string.matches("(?i).*i am.*"); // true if contains but ignore case
// Anywhere in string
b = string.contains("AA") ; // true if contains but ignore case
I have not enough 'reputation points' to reply in the comments, but there is an error in the accepted answer. indexOf() returns -1 when it cannot find the substring, so it should be:
b = string.indexOf("I am") >= 0;
Check out the contains(CharSequence) method
Try this-
etsearch.getText().toString().contains((String) countryCode[i]);
You could use contains. As in:
myString.contains("xxx");
See also: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html, specifically the contains area.
Use the following:
public boolean contains (CharSequence cs)
Since: API Level 1
Determines if this String contains the sequence of characters in the CharSequence passed.
Parameters
cs the character sequence to search for.
Returns
true if the sequence of characters are contained in this string, otherwise false
Actually, the default Arrayadapter class in android only seems to search from the beginning of whole words but by using the custom Arrayadapter class, you can search for parts of the arbitrary string. I have created the whole custom class and released the library. It is very easy to use. You can check the implementation and usage from here or by clicking on the link provided below.
https://github.com/mohitjha727/Advanced-Search-Filter
You can refer to this simple example-
We have names " Mohit " and "Rohan" and if We put " M" only then Mohit shows up in search result, but when we put "oh" then both Mohit and Rohan show up as they have the common letter 'oh'.
Thank You.

Categories