Java: single line substring - java

I need to sub string the string after "2:" to the end of line as it is a changeable string:
Which mean in this example that I want to take the string "LOV_TYPE" from this 2 lines
ObjMgrSqlLog Detail 4 2014-03-26 13:19:58 Bind variable 2: LOV_TYPE
ObjMgrSqlLog Detail 4 2014-03-26 13:19:58 Bind variable 3: AUDIT_LEVEL
I tried to use subString(int startingIndex, int endingIndex) method, I can determine the first argument which is starting point.. but I can't determine the end point.

You can use two substrings, one that gets the String after 2:, and then one that gets the string before the next new line.
string = string.substring(string.indexOf("2:") + 2);
string = string.substring(0, string.indexOf("ObjMgrSqlLog));
If you need to get rid of the spaces on either end, you can then trim the string.
string = string.trim();

source:
String str = "ObjMgrSqlLog Detail 4 2014-03-26 13:19:58 Bind variable 2: LOV_TYPE";
You can use regex
String out1 = str.replaceAll("^.*?.\\:.*[ ]", "");
or classic index-of
int lastCh = str.lastIndexOf(":");
String out2 = str.substring(++lastCh).trim();
output:
System.out.println(out1);
System.out.println(out2);

If you use str.substring(startingIndex), you will have the substring to the end of the string. It seems to be what you want. If you have extra spaces at the end of the string, you can always use a str.trim() to remove the spaces.

Use substring along with .length() to get the value of the length of the string. For example:
String original = "ObjMgrSqlLog Detail 4 2014-03-26 13:19:58 Bind variable 2: LOV_TYPE";
String newString = original.substring (62, original.length ());
System.out.print (newString);

Related

JAVA - How to get text after a particular character?

I have a String Chocolate:30:2 in a variable and I want to extract the number after the second colon i.e. 2. So, How can I extract that number?
For example:
String s = "Chocolate:30:2";
String number = s.split(":")[2];
If the second colon is actually the last colon, you can use:
String after = str.substring(1 + str.lastIndexOf(':'));
You can use String lastIndexOf method.
String result = str.substring(str.lastIndexOf(':') + 1);

How to get the last 3 letters in a string?

I'm trying to get the last three characters in a string. With the following code, I'm trying to get the last three characters of the fname variable, but I'm getting a "The method Length(int) is undefined for the type String" error:
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String number = request.getParameter("number");
String firstPart = lname.substring(0, 3);
String middlePart = fname.substring(0, fname.Length(3));
So there are two problems here:
Firstly you're calling fname.Length(3), which doesn't make sense as String doesn't have a Length(int n) method on it. What it does have is a substring(int) method and a length() method, which you can use as follows:
String middlePart = fname.substring(fname.length() - 3);
As outlined in the linked JavaDocs, String.substring() "Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.". So if we can provide it with the index (or position) within the String fname where we want to start copying from.
If I've got a String such as "Chicken", and I want the last 3 characters, I'd call "Chicken".substring(4), and the result would be "ken" (Strings are zero-indexed, so the character 'k' has index 4).
Instead of hard coding the index where I want to start the substring from, I use the String.length() method which tells me how long a String is, and subtract 3. In the above example, "Chicken".length() is 7, and so "Chicken".length() - 3 is the index where you should start substring-ing if you want the last 3 characters.
String lastThreeChars = string.substring(string.length() - 3);

Getting the last part of the string

I have a string :
"id=40114662&mode=Edit&reminderId=44195234"
All i want from this string is the final number 44195234. I can't use :
String reminderIdFin = reminderId.substring(reminderId.lastIndexOf("reminderId=")+1);
as i cant have the = sign as the point it splits the string. Is there any other way ?
Try String.split(),
reminderIdFin.split("=")[3];
You can use indexOf() method to get where this part starts:
int index = reminderIdFin.indexOf("Id=") + 3;
the plus 3 will make it so that it jumps over these characters. Then you can use substring to pull out your wanted string:
String newString = reminderIdFin.substring(index);
Remove everything else and you'll be left with your target content:
String reminderIdFin = reminderId.replaceAll(".*=", "");
The regex matches everything up to the last = (the .* is "greedy").

Parsing string from the name

I am trying to parse the certain name from the filename.
The examples of File names are
xs_1234323_00_32
sf_12345233_99_12
fs_01923122_12_12
I used String parsedname= child.getName().substring(4.9) to get the 1234323 out of the first line. Instead, how do I format it for the above 3 to output only the middle numbers(between the two _)? Something using split?
one line solution
String n = str.replaceAll("\\D+(\\d+).+", "$1");
most efficent solution
int i = str.indexOf('_');
int j = str.indexOf('_', i + 1);
String n = str.substring(i + 1, j);
String [] tokens = filename.split("_");
/* xs_1234323_00_32 would be
[0]=>xs [1]=> 1234323 [2]=> 00 [3] => 32
*/
String middleNumber = tokens[2];
You can try using split using the '_' delimiter.
The String.split methods splits this string around matches of the given ;parameter. So use like this
String[] output = input.split("_");
here output[1] will be your desired result
ANd input will be like
String input = "xs_1234323_00_32"
I would do this:
filename.split("_", 3)[1]
The second argument of split indicates the maximum number of pieces the string should be split into, in your case you only need 3. This will be faster than using the single-argument version of split, which will continue splitting on the delimiter unnecessarily.

Java - removing first character of a string

In Java, I have a String:
Jamaica
I would like to remove the first character of the string and then return amaica
How would I do this?
const str = "Jamaica".substring(1)
console.log(str)
Use the substring() function with an argument of 1 to get the substring from position 1 (after the first character) to the end of the string (leaving the second argument out defaults to the full length of the string).
public String removeFirstChar(String s){
return s.substring(1);
}
In Java, remove leading character only if it is a certain character
Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.
String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
Prints:
blankstring
foobar
moobar
Java, remove all the instances of a character anywhere in a string:
String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"
Java, remove the first instance of a character anywhere in a string:
String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"
Use substring() and give the number of characters that you want to trim from front.
String value = "Jamaica";
value = value.substring(1);
Answer: "amaica"
You can use the substring method of the String class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.
String str = "Jamaica";
str = str.substring(1);
substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.
The substring begins at the specified start and extends to the character at index end - 1.
It has two forms. The first is
String substring(int FirstIndex)
Here, FirstIndex specifies the index at which the substring will
begin. This form returns a copy of the substring that begins at
FirstIndex and runs to the end of the invoking string.
String substring(int FirstIndex, int endIndex)
Here, FirstIndex specifies the beginning index, and endIndex specifies
the stopping point. The string returned contains all the characters
from the beginning index, up to, but not including, the ending index.
Example
String str = "Amiyo";
// prints substring from index 3
System.out.println("substring is = " + str.substring(3)); // Output 'yo'
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
or in general:
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
public String removeFirst(String input)
{
return input.substring(1);
}
The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.
This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.
I came across a situation where I had to remove not only the first character (if it was a #, but the first set of characters.
String myString = ###Hello World could be the starting point, but I would only want to keep the Hello World. this could be done as following.
while (myString.charAt(0) == '#') { // Remove all the # chars in front of the real string
myString = myString.substring(1, myString.length());
}
For OP's case, replace while with if and it works aswell.
You can simply use substring().
String myString = "Jamaica"
String myStringWithoutJ = myString.substring(1)
The index in the method indicates from where we are getting the result string, in this case we are getting it after the first position because we dont want that "J" in "Jamaica".
Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.
public static String removeLeadingChar(String str, char ch) {
int idx = 0;
while ((idx < str.length()) && (str.charAt(idx) == ch))
idx++;
return str.substring(idx);
}
##KOTLIN
#Its working fine.
tv.doOnTextChanged { text: CharSequence?, start, count, after ->
val length = text.toString().length
if (length==1 && text!!.startsWith(" ")) {
tv?.setText("")
}
}

Categories

Resources