Split method and split on the ‘.’ character (without the csv extension) - java

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("\\.")

Related

Replacing all subsequent characters of a string, after matching a substring

I try to replace a character and all it's following characters within a string with another character.
This is my code so far.
String name = "Peter Pan";
name = name.replace("er", "abc");
Log.d("Name", name)
the result should be: "Petabc"
I would highly appreciate any help on this matter!
A way to achive your goal:
search the string for the first appearance of the sequnce you want to replace
use that index and cut the string using String#substring
add your replace sequence to the end of the substring you just created
fin.
Good luck.
EDIT
In code it might look like this (not tested)
public static String customReplace(String input, String replace)
{
int index = input.indexOf(replace);
if(index >= 0)
{
return input.substring(index) + replace; //cutting string down to the required part and adding the replace
}
else
return null; //String 'input' doesn't contain String 'replace'
}
You could use a Regular Expression here with String's built-in replaceAll method to very easily do what you want:
original.replaceFirst(toReplace + ".*", replaceWith);
For example:
String original = "testing 123";
String toReplace = "ing";
String replaceWith = "er";
String replaced = original.replaceFirst(toReplace + ".*", replaceWith);
After the above, replaced will be set to "tester".

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).

Java Split String Consecutive Delimiters

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

Format name in title case Java help please?

so i have to write a java code to :
Input a name
Format name in title case
Input second name
Format name in title case
Display them in alphabet order
i know that The Java Character class has the methods isLowerCase(), isUpperCase, toLowerCase() and toUpperCase(), which you can use in reviewing a string, character by character. If the first character is lowercase, convert it to uppercase, and for each succeeding character, if the character is uppercase, convert it to lowercase.
the question is how i check each letter ?
what kind of variables and strings should it be contained ?
can you please help?
You should use StringBuilder, whenver dealing with String manipulation.. This way, you end up creating lesser number of objects..
StringBuilder s1 = new StringBuilder("rohit");
StringBuilder s2 = new StringBuilder("jain");
s1.replace(0, s1.length(), s1.toString().toLowerCase());
s2.replace(0, s2.length(), s2.toString().toLowerCase());
s1.setCharAt(0, Character.toTitleCase(s1.charAt(0)));
s2.setCharAt(0, Character.toTitleCase(s2.charAt(0)));
if (s1.toString().compareTo(s2.toString()) >= 0) {
System.out.println(s2 + " " + s1);
} else {
System.out.println(s1 + " " + s2);
}
You can convert the first character to uppercase, and then lowercase the remainder of the string:
String name = "jOhN";
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
System.out.println(name); // John
For traversing Strings using only the String class, iterate through each character in a string.
String s = "tester";
int size = s.length(); // length() is the number of characters in the string
for( int i = 0; i < size; i++) {
// s.charAt(i) gets the character at the ith code point.
}
This question answers how to "change" a String - you can't. The StringBuilder class provides convenient methods for editing characters at specific indices though.
It looks like you want to make sure all names are properly capitalized, e.g.: "martin ye" -> "Martin Ye" , in which case you'll want to traverse the String input to make sure the first character of the String and characters after a space are capitalized.
For alphabetizing a List, I suggest storing all inputted names to an ArrayList or some other Collections object, creating a Comparator that implements Comparator, and passing that to Collections.sort()... see this question on Comparable vs Comparator.
This should fix it
List<String> nameList = new ArrayList<String>();
nameList.add(titleCase("john smith"));
nameList.add(titleCase("tom cruise"));
nameList.add(titleCase("johnsmith"));
Collections.sort(nameList);
for (String name : nameList) {
System.out.println("name=" + name);
}
public static String titleCase(String realName) {
String space = " ";
String[] names = realName.split(space);
StringBuilder b = new StringBuilder();
for (String name : names) {
if (name == null || name.isEmpty()) {
b.append(space);
continue;
}
b.append(name.substring(0, 1).toUpperCase())
.append(name.substring(1).toLowerCase())
.append(space);
}
return b.toString();
}
String has a method toCharArray that returns a newly allocated char[] of its characters. Remember that while Strings are immutable, elements of arrays can be reassigned.
Similarly, String has a constructor that takes a char[] representing the characters of the newly created String.
So combining these, you have one way to get from a String to a char[], modify the char[], and back to a new String.
This can be achieved in any number of ways, most of which will come down to the details of the requirements.
But the basic premise is the same. String is immutable (it's contents can not be changed), so you need away to extract the characters of the String, convert the first character to upper case and reconstitute a new String from the char array.
As has already been pointed out, this is relative simple.
The other thing you might need to do, is handle multiple names (first, last) in a single pass. Again, this is relatively simple. The difficult part is when you might need to split a string on multiple conditions, then you'll need to resort to a regular expression.
Here's a very simple example.
String name = "this is a test";
String[] parts = name.split(" ");
StringBuilder sb = new StringBuilder(64);
for (String part : parts) {
char[] chars = part.toLowerCase().toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
sb.append(new String(chars)).append(" ");
}
name = sb.toString().trim();
System.out.println(name);

Parse this string in Java

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.

Categories