Remove string after second occurrence of comma in java - java

String add_filter = address.split("\\,", 2)[0];
This removes the text after the first comma. I need to remove the text after the second comma without using the loop.

address.split("\\,")[2];
That splits the string around commas. THe 0th index is before the first comma, the 1st is after the 1st comma, the 2nd is after the 2nd comma, etc. Note that this code assumes there's at least 2 commas. If there aren't, you need to save the array returned by split() and check the length to make sure its 3 or higher. Otherwise there was no second comma.

try following code :
//Finding the Nth occurrence of a substring in a String
public static int ordinalIndexOf(String str, String substr, int n) {
int pos = str.indexOf(substr);
while (--n > 0 && pos != -1)
pos = str.indexOf(substr, pos + 1);
return pos;
}
then you can remove string after this index position the same as following code :
String newStr = address.substring(0,ordinalIndexOf(address,",",2)- 1)

Try below code
String s = "Hello,world,good bye";
s = s.replaceFirst(",(.*?),.*", " $1");
System.out.println(s);

Related

Not able to find the indexOf the firstWord after trimming the text

Hey there fellow programmers,
I'm having a little trouble with this program of mine, it's supposed to read in a line of text, then output a line of text so that the first word and the last word are swapped. The only problem is when I try to find the first position in the line after using the trim() method, it sets the index as 0 and doesn't display the firstWord. If someone could gracefully fix & explain my mistake, I would gladly appreciate it. By the way, I am new to programming.
public static void main(String[] args) {
//Text
String txt = " one two three four five";
//use trim method to remove spaces before the firstWord and after lastWord
String firstWord = txt.trim();
String lastWord = txt.trim();
//use indexOf to find the first space position in the line
int index = txt.indexOf(' ');
//use substring to get firstWord and the rest of the line
firstWord = txt.substring(0, index);
//use lastIndexOf to find the last space position in the line
int lastIndex = txt.lastIndexOf(' ');
//use substring to find the last word
lastWord = txt.substring(lastIndex);
//form a new string using concatenation
System.out.println(lastWord + " " + firstWord);
}
When you write
//use trim method to remove spaces before the firstWord and after lastWord
String firstWord = txt.trim();
String lastWord = txt.trim();
you store the trimmed text in variables that you don't use.
Replace these 2 lines with
txt = txt.trim();
And you should get the desired result.
I got your mistake. You were actually trimming the and storing in other variables and using the variable txt in your other code. So you need to trim txt and store in txt itself (or maybe you can store in any other variable but then you will have to use that variable only). Also initializing firstWord and lastWord with trimmed value doesn't make sense since you don't use that value and again initialize it.
public static void main(String[] args) {
//Text
String txt = " one two three four five";
//use trim method to remove spaces before the firstWord and after lastWord
txt = txt.trim();
String firstWord, lastWord;
//use indexOf to find the first space position in the line
int index = txt.indexOf(' ');
//use substring to get firstWord and the rest of the line
firstWord = txt.substring(0, index);
//use lastIndexOf to find the last space position in the line
int lastIndex = txt.lastIndexOf(' ');
//use substring to find the last word
lastWord = txt.substring(lastIndex);
//form a new string using concatenation
System.out.println(lastWord + " " + firstWord);
}
Welcome to the Stackoverflow!
Since your goal is swapping only the first and last words of the line, this could be also achieved with a little help of arrays. Utilizing an array might simplify your code a bit.
If you're trying to achieve this without using arrays, the answer above should help. Otherwise, I would go with something like this:
public static void main(String[] args) {
String txt = " one two three four five";
// use trim method to remove spaces before and after, then split the line into words
String[] words = txt.trim().split(" ");
// Get the first word
var firstWord = words[0];
// Replace the first word with last one
words[0] = words[words.length-1];
// Put the first word to the end
words[words.length-1] = firstWord;
System.out.println(Arrays.toString(words));
}
#Utkarsh Sahu 's answer works fine, but have you considered using split?
String txt = "one two three four five";
String split[];
split = txt.split("\\s+");
System.out.println(split[split.length-1] + " " + split[0]);
I think it's an easier approach.
Issue in Your code is that you trim original string and assigned that to new string (first word & last word). So, the original string is as it is (not trimmed). That’s why you can’t find a proper index. Updated strings are the first word and last word. As shown below use the first word and last word to find index or just use assigned trimmed text to original String and then find out index.
public static void main(String[] args) {
String txt = " one two three four five";
//use trim method to remove spaces before the firstWord and after lastWord
String firstWord = txt.trim();
String lastWord = txt.trim();
//use indexOf to find the first space position in the line
int index = firstWord.indexOf(' ');
//use substring to get firstWord and the rest of the line
firstWord = firstWord.substring(0, index);
//use lastIndexOf to find the last space position in the line
int lastIndex = lastWord.lastIndexOf(' ');
//use substring to find the last word
lastWord = lastWord.substring(lastIndex);
//form a new string using concatenation
System.out.println(lastWord + " " + firstWord);
}
}

Return the number of times that the string "hi" appears anywhere in the given string

I wrote the following Java code, and it returned a time out error. I'm not exactly sure what that means nor why the code doesn't run
public int countHi(String str) {
int pos = str.indexOf("hi");
int count = 0;
while(pos!=-1)
{
count++;
pos = str.substring(pos).indexOf("hi");
}
return count;
}
I know an alternative solution, using a for loop but I really thought this would work too.
You're getting into an infinite loop because pos never advances past the first match as the first match will be included in the substring.
You can fix by using this overridden version of indexOf() inside your while loop:
pos = str.indexOf("hi", pos + 1);
Or use a do... while loop to avoid having to repeat the call to indexOf():
public static int countHi(String str) {
int pos = -1, count = -1;
do {
count++;
pos = str.indexOf("hi", pos + 1);
} while (pos != -1);
return count;
}
str.substring(pos) Output the substring from the given index. therefore in your code while loop never travel through your whole string and its stop at the first "hi".Use this.
while(pos!=-1){
count++;
str = str.substring(pos+2);
pos = str.indexOf("hi");
}
str variable store 2nd half of the string (use +2 for travel two more indexes for end of the hi) then check pos variable store that index of "hi" appear in the new string.
Just for added fun......
If the supplied substring (ie: "hi") is to be counted and it doesn't matter where it is located within the input string (single word or part of a word), you can use a one liner and let the String.replace() method do the job for you by actually removing the desired substring you want to count from the initial input string and calculating what remains of that input string (this does not modify the initial input string):
String inputString = "Hi there. This is a hit in his pocket";
String subString = "hi";
int count = (inputString.length() - inputString.replace(subString, "").
length()) / subString.length())
//Display the result...
System.out.println(count);
Console will display: 3
You will note that the above code is letter case sensitive and therefore in the example above the substring "hi" differs from the word "Hi" because of the uppercase "H" so "Hi" is ignored. If you want to ignore letter case when counting for the supplied substrings then you can use the same code but utilize the String.toLowerCase() method within it:
String inputString = "Hi there. This is a hit in his pocket";
String subString = "hi";
int count = (inputString.length() - inputString.toLowerCase().
replace(substring.toLowerCase(), "").
length()) / substring.length())
//Display the result...
System.out.println(count);
Console will display: 4
If however the supplied substring you want to count is a specific word (not part of another word) then it gets a little more complicated. One way you can do this is by utilizing the Pattern and Matcher Classes along with a small Regular Expression. It could look something like this:
String inputString = "Hi there. This is a hit in his pocket";
String subString = "Hi";
String regEx = "\\b" + subString + "\\b";
int count = 0; // To hold the word count
// Compile the regular expression
Pattern p = Pattern.compile(regEx);
// See if there are matches of subString within the
// input string utilizing the compiled pattern
Matcher m = p.matcher(inputString);
// Count the matches found
while (m.find()) {
count++;
}
//Display the count result...
System.out.println(count);
Console will display: 1
Again, the above code is letter case sensitive. In other words if the supplied substring was "hi" then the display in console would of been 0 since "hi" is different from "Hi" which is in fact contained within the input string as the first word. If you want to ignore letter case then it would just be a matter of converting both the input string and the supplied substring to either all upper case or all lowercase, for example:
String inputString = "Hi there. This is a hit in his pocket";
String subString = "this is";
String regEx = "\\b" + subString.toLowerCase() + "\\b";
int count = 0; // To hold the word count
// Compile the regular expression
Pattern p = Pattern.compile(regEx);
// See if there are matches of subString within the
// input string utilizing the compiled pattern
Matcher m = p.matcher(inputString.toLowerCase());
// Count the matches found
while (m.find()) {
count++;
}
//Display the count result...
System.out.println(count);
Console will display: 1
As you can see in the two most recent code examples above the Regular Expression (RegEx) of "\\bHi\\b" was used (in code, a variable was used in the place of Hi) and here is what it means:

Replace specific character and getting index in Java

I have tried a code to replace only specific character. In the string there are three same characters, and I want to replace the second or third character only. For example:
String line = "this.a[i] = i";
In this string there are three 'i' characters. I want to replace the second or third character only. So, the string will be
String line = "this.a[i] = "newChar";
This is my code to read the string and replace it by another string:
String EQ_VAR;
EQ_VAR = getequals(line);
int length = EQ_VAR.length();
if(length == 1){
int gindex = EQ_VAR.indexOf(EQ_VAR);
StringBuilder nsb = new StringBuilder(line);
nsb.replace(gindex, gindex, "New String");
}
The method to get the character:
String getequals(String str){
int startIdx = str.indexOf("=");
int endIdx = str.indexOf(";");
String content = str.substring(startIdx + 1, endIdx);
return content;
}
I just assume that using an index is the best option to replace a specific character. I have tried using String replace but then all 'i' characters are replaced and the result string look like this:
String line = "th'newChar's.a[newChar] = newChar";
Here's one way you could accomplish replacing all occurances except first few:
String str = "This is a text containing many i many iiii = i";
String replacement = "hua";
String toReplace = str.substring(str.indexOf("=")+1, str.length()).trim(); // Yup, gets stuff after "=".
int charsToNotReplace = 1; // Will ignore these number of chars counting from start of string
// First replace all the parts
str = str.replaceAll(toReplace, replacement);
// Then replace "charsToNotReplace" number of occurrences back with original chars.
for(int i = 0; i < charsToNotReplace; i++)
str = str.replaceFirst(replacement, toReplace);
// Just trim from "="
str = str.substring(0, str.indexOf("=")-1);
System.out.println(str);
Result: This huas a text contahuanhuang many hua many huahuahuahua;
You set set charsToNotReplace to however number of first number of chars you want to ignore. For example setting it to 2 will ignore replacing first two occurrences (well, technically).

get matched elements indexes from string object

Lets say, search string is
"Hellothisissanjayhelloiamjavadeveloperhello"
And Search pattern is * Hello* I want to get starting and ending indexes of each matched strings like
first Hello--- start index=0, end = 4,
second Hello-- start index=22, end = 26,
like this
Split the text by space.
Iterate and group the word matching hello with corresponding index.
corresponding index will be "Hello Start index".
4 corresponding index + 3 will be "end".
You don't need a regex for this solution. Just simple String#indexOf method in a while loop will give you start and end index.
String input = "Hellothisissanjayhelloiamjavadeveloperhello";
String kw = "hello";
String len = kw.length();
String pos = 0;
int i;
while ((i=input.indexOf(kw, pos)) >= 0) {
pos = i +len;
System.out.println("Starting index=%d, end=%d\n", i, pos);
}

Delete one part of the String

I have this String :
String myStr = "something.bad#foo.us"
I want to get just the "something.bad" from myStr ?
You just need to use substring having found the right index to chop at:
int index = myStr.indexOf('#');
// TODO: work out what to do if index == -1
String firstPart = myStr.substring(0, index);
EDIT: Fairly obviously, the above takes the substring before the first #. If you want the substring before the last # you would write:
int index = myStr.lastIndexOf('#');
// TODO: work out what to do if index == -1
String firstPart = myStr.substring(0, index);
You can use
String str = myStr.split("#")[0];
It will split the string in two parts and then you can get the first String element

Categories