Splitting a period-delimited string into multiple strings - java

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

Related

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("*");
}

Checking whether the String contains multiple words

I am getting the names as String. How can I display in the following format: If it's single word, I need to display the first character alone. If it's two words, I need to display the first two characters of the word.
John : J
Peter: P
Mathew Rails : MR
Sergy Bein : SB
I cannot use an enum as I am not sure that the list would return the same values all the time. Though they said, it's never going to change.
String name = myString.split('');
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
String finalName = topTitle + finalName;
The above code fine, but its not working. I am not getting any exception either.
There are few mistakes in your attempted code.
String#split takes a String as regex.
Return value of String#split is an array of String.
so it should be:
String[] name = myString.split(" ");
or
String[] name = myString.split("\\s+);
You also need to check for # of elements in array first like this to avoid exception:
String topTitle, subTitle;
if (name.length == 2) {
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
}
else
topTitle = name.subString(0,1);
The String.split method split a string into an array of strings, based on your regular expression.
This should work:
String[] names = myString.split("\\s+");
String topTitle = names[0].subString(0,1);
String subTitle = names[1].subString(0,1);
String finalName = topTitle + finalName;
First: "name" should be an array.
String[] names = myString.split(" ");
Second: You should use an if function and the length variable to determine the length of a variable.
String initial = "";
if(names.length > 1){
initial = names[0].subString(0,1) + names[1].subString(0,1);
}else{
initial = names[0].subString(0,1);
}
Alternatively you could use a for loop
String initial = "";
for(int i = 0; i < names.length; i++){
initial += names[i].subString(0,1);
}
You were close..
String[] name = myString.split(" ");
String finalName = name[0].charAt(0)+""+(name.length==1?"":name[1].charAt(0));
(name.length==1?"":name[1].charAt(0)) is a ternary operator which would return empty string if length of name array is 1 else it would return 1st character
This will work for you
public static void getString(String str) throws IOException {
String[] strr=str.split(" ");
StringBuilder sb=new StringBuilder();
for(int i=0;i<strr.length;i++){
sb.append(strr[i].charAt(0));
}
System.out.println(sb);
}

string manipulation in java, getting first characters

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

Remove first word from a string in Java

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.

Split a string in java

I am getting this string from a program
[user1, user2]
I need it to be splitted as
String1 = user1
String2 = user2
You could do this to safely remove any brackets or spaces before splitting on commas:
String input = "[user1, user2]";
String[] strings = input.replaceAll("\\[|\\]| ", "").split(",");
// strings[0] will have "user1"
// strings[1] will have "user2"
Try,
String source = "[user1, user2]";
String data = source.substring( 1, source.length()-1 );
String[] split = data.split( "," );
for( String string : split ) {
System.out.println(string.trim());
}
This will do your job and you will receive an array of string.
String str = "[user1, user2]";
str = str.substring(1, str.length()-1);
System.out.println(str);
String[] str1 = str.split(",");
Try the String.split() methods.
From where you are getting this string.can you check the return type of the method.
i think the return type will be some array time and you are savings that return value in string . so it is appending [ ]. if it is not the case you case use any of the methods the users suggested in other answers.
From the input you are saying I think you are already getting an array, don't you?
String[] users = new String[]{"user1", "user2"};
System.out.println("str="+Arrays.toString(str));//this returns your output
Thus having this array you can get them using their index.
String user1 = users[0];
String user2 = users[1];
If you in fact are working with a String then proceed as, for example, #WhiteFang34 suggests (+1).

Categories

Resources