i'm new to Java . How can i obtain right values of each line (second value of the dash separated pair)
Autorul-Stefan
DenumireaCartii-Popovici
CuloareaCartii-Verde
GenulCartii-Religie
Limba-Rusa
SOLVED :
String line = "Autorul-Stefan";
String [] fields = line.split("-");
fields[0] == "Autorul"
fields[1] == "stefan"
String line = "Autorul-Stefan";
String [] fields = line.split("-");
// fields[0] == "Autorul"
// fields[1] == "stefan"
use String.split():
String right = str.split("-")[1];
where str contains your String object
String strings = "Autorul-Stefan";
String[] tempo;
tempo = strings.split("-");
System.out.println(tempo[1]);
You can use the split() function in Strings:
String rightValue = line.split("-")[1];
Where line is the each line of your text (like "Autorul-Stefan") and rightValue is the text to the right of the dash (like "Stefan").
You use [1] to get the second element of the split text (split separates the given String into an array using the given character (here "-") as a divider) So in this example, the first element of the array is the text to the left of the dash and the second element is the text to the right of the dash.
Related
Modify the constructor so that the name field is set to the filename
without the .csv extension. Hint: use the split method and split on
the ‘.’ character.
I used
filename.split('.');
public DataSet(String filename, color dataSetColor){
name = filename;
_dataSetColor = dataSetColor;
_markList = new ArrayList<StudentMarks>();
linesArray = loadStrings(filename);
for(String l : linesArray){
//Split the current line storing the values in csvArray
csvArray = split(l, ',');
if(csvArray.length == 3){
String id = csvArray[0];
int internalM = Integer.parseInt(csvArray[1]);
int ExamM = Integer.parseInt(csvArray[2]);
_markList.add(new StudentMarks(id,internalM,ExamM,_dataSetColor));
} else {
println("The length of the csvArray is not equal to 3");
}
}
}
when I ran this, I want the result shows "dataSet", not the "dataSet.csv"
Just change one line (use split with escape):
name = filename.split("\\.")[0];
The problem is dot is a special symbol you need to escape.
One more solution is to use lastIndexOf method and substring:
name = fileneme.substring(0, filename.lastIndexOf("."));
Second solution will work for the case when you'll have dots in file name.
You can split a string by '.' using filename.split("\\.")
I want to keep all the characters before a space and remove the rest of the string.
Example:
String str = "Davenport FL 33897 US";
I want to print only "Davenport" and remove the rest of the string. Also the string is dynamic every time.
You need to use substr and indexOf
str.substr(0,str.indexOf(' ')); // "Davenport"
substr(0,X) will give you the sub string of your string starting at index 0 and ending at index X,
Because you want to get the first word until the first space you replace X with:
str.indexOf(' ')
which returns the index of the first space in your string
We can use regular expression to detect space and special character. You can utilize below code to do the same.
String str="Davenport FL 33897 US";
String[] terms = str.split("[\\s#&.?$+-]+");
System.out.println(terms[0]);
It's working for me.
You can use the split function to split the string using ' ' as your delimeter.
const myString = "Davenport FL 33897 US"
const splitString = myString.split(' ')
split() returns an array of strings that separated using the delimeter.
you can just get the index of the first string by.
console.log(splitString[0])
another way would be just to put the index after the split function so that you get only what you want and not the full array.
const firstWord = myString.split(' ')[0]
String[] newOutput = str.split(" ");
String firstPart = newOutput[0];
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).
I have a need to split a string that is passed in to my app from an external source. This String is delimited with a caret "^" and here is how I split the String into an Array
String[] barcodeFields = contents.split("\\^+");
This works fine except that some of the passed in fields are empty and I need to account for them. I need to insert either "" or "null" or "empty" into any missing field.
And the missing fields have consecutive delimiters. How do I split a Java String into an array and insert a string such as "empty" as placeholders where there are consecutive delimiters?
The answer by mureinik is quite close, but wrong in an important edge case: when the trailing delimiters are in the end. To account for that you have to use:
contents.split("\\^", -1)
E.g. look at the following code:
final String line = "alpha ^beta ^^^";
List<String> fieldsA = Arrays.asList(line.split("\\^"));
List<String> fieldsB = Arrays.asList(line.split("\\^", -1));
System.out.printf("# of fieldsA is: %d\n", fieldsA.size());
System.out.printf("# of fieldsB is: %d\n", fieldsB.size());
The above prints:
# of fieldsA is: 2
# of fieldsB is: 5
String.split leaves an empty string ("") where it encounters consecutive delimiters, as long as you use the right regex. If you want to replace it with "empty", you'd have to do so yourself:
String[] split = barcodeFields.split("\\^");
for (int i = 0; i < split.length; ++i) {
if (split[i].length() == 0) {
split[i] = "empty";
}
}
Using ^+ means one (or more consecutive) carat characters. Remove the plus
String[] barcodeFields = contents.split("\\^");
and it won't eat empty fields. You'll get (your requested) "" for empty fields.
The following results in [blah, , bladiblah, moarblah]:
String test = "blah^^bladiblah^moarblah";
System.out.println(Arrays.toString(test.split("\\^")));
Where the ^^ are replaced by a "", the empty String
I have this string,
anyType{image0=images/articles/4_APRIL_BLACK_copy.jpg; image1=images/articles/4_APRIL_COLOR_copy.jpg; }
What i want is only
"images/articles/4_APRIL_BLACK_copy.jpg"
How do i get this?
This is how I perform a split in my app.
String link = "image0=images/articles/4_APRIL_BLACK_copy.jpg";
String[] parts = link.split("=");
String first = parts[0];
Log.v("FIRST", first);
String second = parts[1];
Log.v("SECOND", second);
This method will split your string into 2 at the "=" and give you 2 split strings. In your case, the String second is the result you want.
This should work:
s.split("=")[1]
You are splitting the string on = which would return substrings in an array. The second element is what you need.