Java Character change of a String - java

i have java String variables format with(include spaces) String id = "CA T 4443" i need to get my String value as id=CA4443 need to remove T and spaces. can any java expert help me to concatenate these characters.
my value array
CA T 4443
CB T 4562
CG T 6365
DA T 5552
CX T 9875
CS T 5454
RA T 2377
second challenge
CAF T 444352
CBAD T 4562
CG T 636535
DA T 555255
CX T 98755665
CS T 545455
RA T 237766
i need to get as (only 1st two latter and last 4 digits)
CA4352
CB4562
CG6535
DA5255
CX5665
CS5455
RA7766

If it is always two lettes, a space, a T, and a number then you could do :
String id = "CA T 4443"
String result = id.substring(0, 2) + id.substring(5, id.length);
Or you could just do :
String result = id.replace(" T ", "");

Just do this:
public static String getFormatedValue(String data) {
String[] split = data.split(" ", 3);
return split[0] + split[2];
}
This will take the first and last section, and skip the middle T section.

You have several things going on - it's hard to tell what's the best approach without seeing the raw data.
easiest / most fragile: if you know for a fact that every line is exactly the same length, "CA T 4443" you can just manually grab the characters at that position with substring or directly from the char array. This will break if one line is larger, probably safer to trim() the string before calling substring
or you can call split:
String id = "CA T 4443";
String[] split = id.split(" "); -> gives ["CA","T", "4443"]
A bit more flexible with lengths but depends on formatting. Splitting on a regex for whitespace if your data is possibly dirty
or just grab pieces through regex matching.
Depends on how normalized your data is.

EDIT: For the firtst challenge only
If it is always that the IDs have T between the two "segments" you are trying to concatenate, then following is my solution:
public static String makeID(String[] myValueArray){
String newID = "";
for (String s: myValueArray){
String[] previousID = s.split(" T ");
newID = newID + previousID[0] + previousID[1] + "\n";
}
return newID;
}

Related

Splitting string in java

I have input as follows
Date Place total trains
monday,chennai,10
tuesday,kolkata,20
wednesday,banglore,karnataka,30
I want to split this data.So far I have used
String[] data = input.split(",");
If I do like above I am getting
index[0] index[1] index[2]
monday chennai 10
tuesday kolkata 20
wednesday banglore karnataka 30
But I want the output like below
index[0] index[1] index[3]
wednesday banglore,karnataka 30
Is there any way to achieve this
Split your input according to the first comma or the last comma.
String s = "wednesday,banglore,karnataka,30";
String parts[] = s.split("(?<=^[^,]*),|,(?=[^,]*$)");
System.out.println(Arrays.toString(parts));
Output:
[wednesday, banglore,karnataka, 30]
If you split a string with a regex, you essentially tell where the string should be cut. This necessarily cuts away what you match with the regex. Which means if you split at \w, then every character is a split point and the substrings between them (all empty) are returned. Java automatically removes trailing empty strings, as described in the documentation.
This also explains why the lazy match \w*? will give you every character, because it will match every position between (and before and after) any character (zero-width). What's left are the characters of the string themselves
Try
String[] data = input.split("(?<=^\\w+),|,(?=\\d+)");
Some good Explanations is here
Sticking to the basics, your data has to be in this format.
Date,Place,total trains
"monday","chennai","10"
"tuesday","kolkata","20"
"wednesday",'banglore,karnataka","30"
Because, if both delimiter and data are same, then either write a complex code to handle to simply put your data in double quotes. csv files also uses this feature.
Assuming you know the position of "," you can get rid of it.
Program below replaces 2nd instance of , with " " so string.split() works as needed
need to import import java.util.regex.*;
===========
public static void main(String args[]){
StringBuffer sb = new StringBuffer();
String s = "wednesday,banglore,karnataka,30";
Pattern p = Pattern.compile(",");
Matcher m = p.matcher(s);
int count = 1;
while(m.find()) {
if(count == 2 ){
m.appendReplacement(sb, " ");
}
count++;
}
m.appendTail(sb);
System.out.println(sb);
s= sb.toString();
String[] data = s.split(",");
System.out.println( data[0] + "-" + data[1] + "-" +data[2] );
}//psvm
Output
wednesday,banglore karnataka,30
wednesday-banglore karnataka-30
This code will work for you :
public static void main(String[] args) {
String s1 = "wednesday,banglore,karnataka,30";
String s2 = "monday,chennai,10";
String[] arr1 = s1.split("(?<=^\\w+),|,(?=\\d+)");
for(String ss : arr1)
System.out.println(ss);
System.out.println();
String[] arr2 = s2.split("(?<=^\\w+),|,(?=\\d+)");
for(String ss : arr2)
System.out.println(ss);
}
O/P :
wednesday
banglore,karnataka
30
monday
chennai
10

Remove trailing substring from String in Java

I am looking to remove parts of a string if it ends in a certain string.
An example would be to take this string: "am.sunrise.ios#2x.png"
And remove the #2x.png so it looks like: "am.sunrise.ios"
How would I go about checking to see if the end of a string contains "#2x.png" and remove it?
You could check the lastIndexOf, and if it exists in the string, use substring to remove it:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
int index = str.lastIndexOf(search);
if (index > 0) {
str = str.substring(0, index);
}
Assuming you have a string initialized as String file = "am.sunrise.ios#2x.png";.
if(file.endsWith("#2x.png"))
file = file.substring(0, file.lastIndexOf("#2x.png"));
The endsWith(String) method returns a boolean determining if the string has a certain suffix. Depending on that you can replace the string with a substring of itself starting with the first character and ending before the index of the character that you are trying to remove.
private static String removeSuffixIfExists(String key, String suffix) {
return key.endswith(suffix)
? key.substring(0, key.length() - suffix.length())
: key;
}
}
String suffix = "#2x.png";
String key = "am.sunrise.ios#2x.png";
String output = removeSuffixIfExists(key, suffix);
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
word = word.replace("#2x.png", "");
System.out.println(word);
}
If you want to generally remove entire content of string from # till end you can use
yourString = yourString.replaceAll("#.*","");
where #.* is regex (regular expression) representing substring starting with # and having any character after it (represented by .) zero or more times (represented by *).
In case there will be no #xxx part your string will be unchanged.
If you want to change only this particular substring #2x.png (and not substirng like #3x.png) while making sure that it is placed at end of your string you can use
yourString = yourString.replaceAll("#2x\\.png$","");
where
$ represents end of string
\\. represents . literal (we need to escape it since like shown earlier . is metacharacter representing any character)
Since I was trying to do this on an ArrayList of items similarly styled I ended up using the following code:
for (int image = 0; image < IBImages.size(); image++) {
IBImages.set(image, IBImages.get(image).split("~")[0].split("#")[0].split(".png")[0]);
}
If I have a list of images with the names
[am.sunrise.ios.png, am.sunrise.ios#2x.png, am.sunrise.ios#3x.png, am.sunrise.ios~ipad.png, am.sunrise.ios~ipad#2x.png]
This allows me to split the string into 2 parts.
For example, "am.sunrise.ios~ipad.png" will be split into "am.sunrise.ios" and "~ipad.png" if I split on "~". I can just get the first part back by referencing [0]. Therefore I get what I'm looking for in one line of code.
Note that image is "am.sunrise.ios~ipad.png"
You could use String.split():
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
String[] parts = word.split("#");
if (parts.length == 2) {
System.out.println("looks like user#host...");
System.out.println("User: " + parts[0]);
System.out.println("Host: " + parts[1]);
}
}
Then you haven an array of Strings, where the first element contains the part before "#" and the second element the part after the "#".
Combining the answers 1 and 2:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
if (str.endsWith(search)) {
str = str.substring(0, str.lastIndexOf(search));
}

String split function in Java

I have a String and I want to split it by ","
If suppose I have a String like,
String test = "aa,bb,cc";
now I can split it by,
String[] spl = test.split(",");
And the spl.length is 3
If suppose my String is
String test = ",,,";
Here the splitted String length is 0. But my expected answer is 3.
My test String is dynamaic value and it may varies like, Now think I have a String like
String test = ",aa,dd,,,,,ff,gg"
Now the splited array length is 4. But I expected answer is 9
And I need to split by "," and I need the aa position at spl[1] and dd position as spl[2] and ff position as spl[7]
Can someone give the suggestion about to solve this issue..
Use split() with -1 as limit
public static void main(String[] args) {
String test = ",,,";
System.out.println(Arrays.toString(test.split(",", -1))); // adds leading and trailing empty Strings .
// so effectively its like adding "" before , after and between each ","
String test1 = "aa,bb,cc";
System.out.println(Arrays.toString(test1.split(",",-1)));
}
O/P :
[, , , ] -- > Length =4
[aa, bb, cc]
To get the behavior you want you can just replace "," by " ,":
String test = ",,";
test = test.replace(",", " ,");
System.out.println((test.split(",").length));
With the split() function, java separates a String by the Substring of your choice. If there is nothing between them, the field will not be null, it will just be skipped.
In other programming languages, you could come across something like this:
String example = ',,,'
String[] example2 = example.split(',')
print(example2.length())
This could also deliver 4. Because there are 4 spaces around the ',' chars:
1,2,3,4

Part I - Java Split String function

I am still new at java. I have this basic split string function as below. I need to capture the substrings post split. My question is how to move individually split parts into separate variables instead of printing them? Do I need another array to move them separately? Is there another simpler way to achieve this? In part I, for simplicity, I am assuming the delimiters to be spaces. Appreciate your help!
public class SplitString {
public static void main(String[] args) {
String phrase = "First Second Third";
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
String first;
String middle;
String last;
for (int i = 0; i < tokens.length; i++)
{
System.out.println(tokens[i]);
//I need to move first part to first and second part to second and so on
}
}
}
array[index] accesses the indexth element of array, so
first = tokens[0]; // Array indices start at zero, not 1.
second = tokens[1];
third = tokens[2];
You should really check the length first, and if the string you're splitting is user input, tell the user what went wrong.
if (tokens.length != 3) {
System.err.println(
"I expected a phrase with 3 words separated by spaces,"
+ " not `" + phrase + "`");
return;
}
If the number of Strings that you will end up with after the split has taken place is known, then you can simply assign the variables like so.
String first = tokens[0];
String middle = tokens[1];
String last = tokens[2];
If the number of tokens is not known, then there is no way (within my knowledge) to assign each one to a individual variable.
If you're assuming that your String is three words, then it's quite simple.
String first = tokens[0];
String middle = tokens[1];
String last = tokens[2];
if(tokens.length>3)
{
String first=tokens[0];
String middle=tokens[1];
String last=tokens[2];
}
Thanks everyone...all of you have answered me in some way or the other. Initially I was assuming only 3 entries in the input but turns out it could vary :) for now i'll stick with the simple straight assignments to 3 variables until I figure out another way! Thanks.

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.

Categories

Resources