string manipulation in java, getting first characters - java

Lets say I have a string whose format is "name_surname". I mean there are 2 dynamic parts, and between them an underscore. I want to separate them and have in a variable the left part (name) and in another the right (surname).
Basically i want the reverse of this: String temp=name+"_"+surname;

Use split();
String[] parts = temp.split("_");
String name = parts[0];
String surname = parts[1]; // <-- comment
Commented line will throw an ArrayIndexOutOfBoundsException if your name does not contain the underscore.

You should use split.
String fullName = "name_surname";
String[] components = fullName.split("_");
String firstName = components[0];
String lastName = components[1];

Just use StringTokenizer
StringTokenizer st = new StringTokenizer(str, "_");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}

Related

How can get string which seprated by delimeted symbol ( | ) in text file using java?

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

Java string split with multiple delimeters

What would be the best way to split this string directly after the CN= to store both the first and last name in separate fields as shown below?
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String firstName"Paul"
String lastName="Sebula"
Don't re-invent the wheel. Assuming these are well-formed DN's, see the accepted answer on this question for how to parse without directly writing your own regex: Parsing the CN out of a certificate DN
Once you've extracted the CN, then you can apply some of the other parsing techniques suggested (use the Java StringTokenizer or the String.split() method as others here have suggested if it's known to be separated only by spaces). That assumes that you can make assumptions (eg. the first element in the resulting array is the firstName,the last element is the lastName and everything in between is middle names / initials) about the CN format.
You can use split:
String distinguisedName = "CN=Paul Sebula,OU=BAE,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=baesystems,DC=com";
String[] names = distinguisedName.split(",")[0].split("=")[1].split(" ");
String firstName = names[0];
String lastName= names.length > 2 ? names[names.length-1] : names[1];
System.out.println(firstName + " " + lastName);
See IDEONE demo, output: Paul Sebula.
This also accounts for just 2 names (first and last only). Note how last name is accessed it being the last item in the array.
public static void main(String[] args) {
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String splitResult[]=distinguisedName.split(",")[0].split("=");
String resultTwo[]=splitResult[1].split("\\.");
String firstName=resultTwo[0].split(" ")[0].trim();
String lastName=resultTwo[1].trim();
System.out.println(firstName);
System.out.println(lastName);
}
output
Paul
Sebula
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String[] commaSplit = distinguisedName.split(',');
String[] whitespaceSplit = commaSplit[0].split(' ');
String firstName = whitespaceSplit[0].substring(3);
String lastName = whiteSpaceSplit[2];
In steps:
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String fullName = distinguisedName.substring(3, distinguisedName.indexOf(','));
String[] nameParts = fullName.split(" ");
String firstName = nameParts[0];
String lastName = nameParts[nameParts.length-1];
This will work for cases where the middle name/initial are not present as well.

Java get the same String after split

In Java if you want to split a String by a char or a String you can do that by the split method as follow:
String[] stringWords = myString.split(" ");
But let's say i want now to create a new String using the strings in stringWords using the char * between them. Is there any solutions to do it without for/while instructions?
Here is a clear example:
String myString = "This is how the string should be";
String iWant = "This*is*how*the*string*should*be";
Somebody asks me to be more clear why i don't want just to use replace() function. I don't want to use it simply because the content of the array of strings (array stringWords in my example) changes it's content.
Here is an example:
String myString = "This is a string i wrote"
String[] stringWords = myString.split(" ");
myAlgorithmFucntion(stringWords);
Here is an example of how tha final string changes:
String iWant = "This*is*something*i*wrote*and*i*don't*want*to*do*it*anymore";
If you don't want to use replace or similar, you can use the Apache Commons StringUtils:
String iWant = StringUtils.join(stringWords, "*");
Or if you don't want to use Apache Commons, then as per comment by Rory Hunter you can implement your own as shown here.
yes there is solution to, split String with special characters like '*','.' etc. you have to use special backshlas.
String myString = "This is how the string should be";
iWant = myString.replaceAll(" ","*"); //or iWant = StringUtils.join(Collections.asList(myString.split(" ")),"*");
iWant = "This*is*how*the*string*should*be";
String [] tab = iWant.split("\\*");
Try something like this as you don't want to use replace() function
char[] ans=myString.toCharArray();
for(int i =0; i < ans.length; i++)
{
if(ans[i]==' ')ans[i]='*';
}
String answer=new String(ans);
Try looping the String array:
String[] stringWords = myString.split(" ");
String myString = "";
for (String s : stringWords){
myString = myString + "s" + "*";
}
Just add the logic to deleting the last * of the String.
Using StringBuilder option:
String[] stringWords = myString.split(" ");
StringBuilder myStringBuilder = new StringBuilder("");
for (String s : stringWords){
myStringBuilder.append(s).append("*");
}

Separate one String with ',' character into two new String

A MySQL table called item_list has a field named description, the problem is the previous programmer combined the name and description of the item in one field called description. The data is now at 20k+. Now I am going to have a problem during migration.So how do I separate one
String description="BEARING, ROLLER 23230CKE4 SPHERICAL"
into two new strings
String name="BEARING"
String description="ROLLER 23230CKE4 SPHERICAL"
Any help will be appreciated.
you can try this way
String description="BEARING, ROLLER 23230CKE4 SPHERICAL";
String [] arr=description.split(",");
System.out.println(arr[0]);
System.out.println(arr[1]);
output
BEARING
ROLLER 23230CKE4 SPHERICAL
String Split methods returns an array of strings.As in the String description has one comma(,) So the whole string will be splited into 2 strings.
You can use StringTokenizer
something like this
StringTokenizer st = new StringTokenizer(description,",");
String name=st.nextToken();
description=st.nextToken();
Unfortunately string split functions will not work correctly if there is more than 1 , in the combined string.
I recommend you split on the first , only.
int idx = description.indexOf(',');
if (idx != -1) { // if there is a comma
name = description.substring(0, idx);
description = description.substring(idx+1);
} else {
???? // no comma in description
}
combination of all the answers.., that solve the problem.
String name="",new_d ="";
String description="BEARING, ROLLER 23230CKE4 SPHERICAL";
int idx = description.indexOf(',');
if (idx != -1) { // if there is comma
String arr[]=description.split(",\\s*");
name=arr[0].toString();
new_d=arr[1].toString();
}
else {
// if there is no comma
name=description;
new_d="";
}
System.out.println(name);
System.out.println(new_d);

Splitting a period-delimited string into multiple strings

I have a string
String x = "Hello.August 27th.Links.page 1";
I am wondering if I can split this string into 4 other strings based on where the period is. For example, the four other strings would be,
String a = "Hello";
String b = "August 27th";
String c = "Links";
String d = "page 1";
As you can see I basically want to extract certain parts of the string out into a new string, the place where it is extracted is based on where the period is which ends the first string and then shows where the 2nd and, etc. strings end.
Thanks in advance!
In android btw
Use String#split (note that it receives a regex as a parameter)
String x = "Hello.August 27th.Links.page 1";
String[] splitted = x.split("\\.");
Yes of course just use:
String[] stringParts = myString.split("\\.")
String x = "Hello.August 27th.Links.page 1"
String []ar=x.split("[.]");
Perhaps you can use StringTokenizer for this requirement. Here is the simple approach:
String x = "Hello.August 27th.Links.page 1";
if (x.contains(".")) {
StringTokenizer stringTokenizer = new StringTokenizer(x, ".");
String[] arrayOfString = new String[stringTokenizer.countTokens()];
int i = 0;
while (stringTokenizer.hasMoreTokens()) {
arrayOfString[i] = stringTokenizer.nextToken();
i++;
}
System.out.println(arrayOfString[0]);
System.out.println(arrayOfString[1]);
System.out.println(arrayOfString[2]);
System.out.println(arrayOfString[3]);
}
You are done. :)

Categories

Resources