I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?
while (in.hasNextLine()) {
String temp = in.nextLine().replaceAll("[<>]", "");
temp.trim();
String nickname = temp.substring(temp.indexOf(' '));
String content = temp.substring(' ' + temp.length()-1);
System.out.println(content);
Use the java.lang.String split function with a limit.
String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));
You will get:
cr: some, cdr: string with spaces
Must be some around this:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.split(" ",2)
split takes a limit input restricting the number of times the pattern is applied.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex.
But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
Related
I having test file in my java project directory which having below content:
HEADER|INPUT|2017|test|1
|Id|Name|
From where I want to update " Id " value from another string "xyz"
"ID" is not static everytime this value gets changed
How can I get particular string using java?
You can use the split function. This will return your string split into the parts, seperated by |.
var result = "HEADER|INPUT|2017|test|1 |Id|Name|".split("\\|");
// Access an array
// result[0] will be 'Header'
Source
You can use String.split() function:
String string = "HEADER|INPUT|2017|test|1 |Id|Name|";
String[] parts = string.split("\\|");
String part1 = parts[0]; // HEADER
String part2 = parts[1]; // INPUT
String part3=parts[2]; //2017
and so on.
You can make use of split() method here to divide your string as per your requirement.
String input= "HEADER|INPUT|2017|test|1 |Id|Name|";
String[] contents = input.split("\\|");
String name = input[6];
String id = input[5];
String number = input[4];
String test = input[3];
String year = input[2];
String input = input[1];
String header = input[0];
For more on String.split()
I want to remove a part of string from one character, that is:
Source string:
manchester united (with nice players)
Target string:
manchester united
There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.
For example
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
Use String.Replace():
http://www.daniweb.com/software-development/java/threads/73139
Example:
String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");
https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()
Using StringBuilder, you can replace the following way.
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.
String[] output = originalString.split(" (");
String result = output[0];
Using StringUtils from commons lang
A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.
String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
If you just need to remove everything after the "(", try this. Does nothing if no parentheses.
StringUtils.substringBefore(str, "(");
If there may be content after the end parentheses, try this.
String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")");
To remove end spaces, use str.trim()
Apache StringUtils functions are null-, empty-, and no match- safe
Kotlin Solution
If you are removing a specific string from the end, use removeSuffix (Documentation)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
If the suffix does not exist in the string, it just returns the original
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
If you want to remove after a character, use
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar
The Full List is here: (Documentation)
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched
String[] operatorList = { "name", "first_name", "last_name", "city" };
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
for (String opElement : operatorList) {
if (originalString.contains(opElement)) {
String tempStr = originalString.replace(opElement, "user." + opElement);
originalString = tempStr;
}
}
System.out.println("originalString " + originalString);
Output:
user.city=Houston^ORlast_user.name=Cervantsz^ORfirst_user.name=John^user.name=don
When i am trying to replace name with "user.name" at that time name from "last_name" is replaced with "last_user.name" and first_name with first_user.name
But i want replace "name" with "user.name" and "last_name" with "user.last_name"
and "first_name" with "user.first_name".
Any help appreciated.
You can add prefix all key and control that key. Example
String[] operatorList = {"name", "first_name", "last_name", "city"};
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^ORname=don";
for (String opElement : operatorList) {
if (originalString.contains("^OR"+opElement)) {
String tempStr = originalString.replace(opElement, "user." + opElement);
originalString = tempStr;
}
}
System.out.println("originalString " + originalString);
If the values you are trying to change are always unique and generated (meaning they are always in the same order), you can simply put your operators in the same order and use replaceLast() instead.
A more complete solution would be to determine how the string is constructed. Do all the values have a ^ in front of them? Is OR generated for the same values or is it to indicate optional values?. So in the end, what allows you to split the string properly. Then you can use a Regex to use the surrounding characters.
I would format the string to make sure the splitters are constant (all "^OR" become "##%!!" and all remaining "^" become "%!!") so all replaced strings start with !!. Then I would reformat the string to the original format using the remaining "##%" or "%" :
String[] operatorList = { "name", "first_name", "last_name", "city" };
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
originalString = originalString.replaceAll("\\^OR", "##%!!");
originalString = originalString.replaceAll("\\^", "%!!");
//the order is important here
for (String opElement : operatorList) {
if (originalString.startsWith(opElement)) {
originalString = originalString.replaceFirst(opElement, "user." + opElement);
}
originalString = originalString.replaceAll("!!" + opElement, "user." + opElement);
// no need for an other alternative here because replaceAll returns the
// String as is if it does not find the first parameter in the String.
}
originalString = originalString.replaceAll("##%", "^OR");
originalString = originalString.replaceAll("%", "^");
// the order here is also important
outputs : "user.city=Houston^ORuser.last_name=Cervantsz^ORuser.first_name=John^user.name=don"
If all keypairs need prefix "user.", I would like to split originalString first.
In Java8
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
String[] params = originalString.split("\\^");
String result = String.join("^", Arrays.stream(params)
.map(param -> param.startsWith("OR") ? "ORuser." + param.substring(2) : "user." + param)
.collect(Collectors.toList()));
System.out.println(result);
It can also be changed to for loop type.
You may use a quick search and replace with an alternation based pattern created dynamically from the search words only when they are preceded with a word boundary or ^ + OR/AND/etc. operators and followed with a word boundary. Note that this solution assumes the search words only consist of word chars (letters, digits or _):
String[] operatorList = { "name", "first_name", "last_name", "city" };
// assuming operators only consist of word chars
String pat = "(\\b|\\^(?:OR|AND)?)(" + String.join("|", operatorList) + ")\\b";
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
originalString = originalString.replaceAll(pat, "$1user.$2");
System.out.println(originalString);
// => user.city=Houston^ORuser.last_name=Cervantsz^ORuser.first_name=John^user.name=don
See the Java demo online
The regex will look like
(\b|\^(?:OR|AND)?)(name|first_name|last_name|city)\b
See the regex demo.
Details
(\b|\^(?:OR|AND)?) - Group 1: a word boundary \b or a ^ symbol and an optional substring, OR or AND (you may add more here after |)
(name|first_name|last_name|city) - Group 2: any of the search words
\b - a trailing word boundary.
The $1 in the replacement pattern inserts the contents of Group 1 and $2 does the same with Group 2 contents.
I am trying to create string of this list without the following character , [] as will I want to replace all two spaces after deleting them.
I have tried the following but I am geting the error in the title.
Simple:
[06:15, 06:45, 07:16, 07:46]
Result should look as this:
06:15 06:45 07:16 07:46
Code:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll(",", " ");
String after2 = after.replaceAll(" ", " ");
String after3 = after2.replaceAll("[", "");
String after4 = after3.replaceAll("]", "");
replaceAll replaces all occurrences that match a given regular expression. Since you just want to match a simple string, you should use replace instead:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace(" ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
To answer the main question, if you use replaceAll, make sure your 1st argument is a valid regular expression. For your example, you can actually reduce it to 2 calls to replaceAll, as 2 of the substitutions are identical.
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll("[, ]", " ");
String after2 = after.replaceAll("\\[|\\]", "");
But, it looks like you're just trying to concatenate all the elements of a String list together. It's much more efficient to construct this string directly, by iterating your list and using StringBuilder:
StringBuilder builder = new StringBuilder();
for (String timeEntry: entry.getValue()) {
builder.append(timeEntry);
}
String after = builder.toString();
What's the best way to remove the first word from a string in Java?
If I have
String originalString = "This is a string";
I want to remove the first word from it and in effect form two strings -
removedWord = "This"
originalString = "is a string;
Simple.
String o = "This is a string";
System.out.println(Arrays.toString(o.split(" ", 2)));
Output :
[This, is a string]
EDIT:
In line 2 below the values are stored in the arr array. Access them like normal arrays.
String o = "This is a string";
String [] arr = o.split(" ", 2);
arr[0] // This
arr[1] // is a string
You can use substring
removedWord = originalString.substring(0,originalString.indexOf(' '));
originalString = originalString.substring(originalString.indexOf(' ')+1);
This will definitely a good solution
String originalString = "This is a string";
originalString =originalString.replaceFirst("This ", "");
Try this using an index var, I think it's quite efficient :
int spaceIdx = originalString.indexOf(" ");
String removedWord = originalString.substring(0,spaceIdx);
originalString = originalString.substring(spaceIdx);
Prior to JDK 1.7 using below method might be more efficient, especially if you are using long string (see this article).
originalString = new String(originalString.substring(spaceIdx));
For an immediate answer you can use this :
removeWord = originalString.substring(0,originalString.indexOf(' '));
originalString = originalString.substring(originalString.indexOf(' '));
You can check where is the first space character and seperate string.
String full = "Sample Text";
String cut;
int pointToCut = full.indexOf( ' ');
if ( offset > -1)
{
cut = full.substring( space + 1);
}
String str = "This is a string";
String str2=str.substring(str.indexOf(" "));
String str3=str.replaceFirst(str2, "");
String's replaceFirst and substring
also you can use this solution:
static String substringer(String inputString, String remove) {
if (inputString.substring(0, remove.length()).equalsIgnoreCase(remove)) {
return inputString.substring(remove.length()).trim();
}
else {
return inputString.trim();
}
}
Example :
substringer("This is a string", "This");
You can use the StringTokenizer class.