Remove first word from a string in Java - 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.

Related

How to split a string from the first space occurrence only Java

I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?
while (in.hasNextLine()) {
String temp = in.nextLine().replaceAll("[<>]", "");
temp.trim();
String nickname = temp.substring(temp.indexOf(' '));
String content = temp.substring(' ' + temp.length()-1);
System.out.println(content);
Use the java.lang.String split function with a limit.
String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));
You will get:
cr: some, cdr: string with spaces
Must be some around this:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.split(" ",2)
split takes a limit input restricting the number of times the pattern is applied.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex.
But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.

Java PatternSyntaxException when replacing characters in a String object

I am trying to create string of this list without the following character , [] as will I want to replace all two spaces after deleting them.
I have tried the following but I am geting the error in the title.
Simple:
[06:15, 06:45, 07:16, 07:46]
Result should look as this:
06:15 06:45 07:16 07:46
Code:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll(",", " ");
String after2 = after.replaceAll(" ", " ");
String after3 = after2.replaceAll("[", "");
String after4 = after3.replaceAll("]", "");
replaceAll replaces all occurrences that match a given regular expression. Since you just want to match a simple string, you should use replace instead:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace(" ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
To answer the main question, if you use replaceAll, make sure your 1st argument is a valid regular expression. For your example, you can actually reduce it to 2 calls to replaceAll, as 2 of the substitutions are identical.
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll("[, ]", " ");
String after2 = after.replaceAll("\\[|\\]", "");
But, it looks like you're just trying to concatenate all the elements of a String list together. It's much more efficient to construct this string directly, by iterating your list and using StringBuilder:
StringBuilder builder = new StringBuilder();
for (String timeEntry: entry.getValue()) {
builder.append(timeEntry);
}
String after = builder.toString();

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

Easiest way to get every word except the last word from a string

What is the easiest way to get every word in a string other than the last word in a string?
Up until now I have been using the following code to get the last word:
String listOfWords = "This is a sentence";
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];
And then getting the rest of the the string by using the remove method to remove the last word from the string.
I don't want to have to use the remove method. Is there a way similar to the above set of code to get the string of words without the last word and last space?
Like this:
String test = "This is a test";
String firstWords = test.substring(0, test.lastIndexOf(" "));
String lastWord = test.substring(test.lastIndexOf(" ") + 1);
You could get the lastIndexOf the white space and use a substring like below:
String listOfWords = "This is a sentence";
int index = listOfWords.lastIndexOf(" ");
System.out.println(listOfWords.substring(0, index));
System.out.println(listOfWords.substring(index+1));
Output:
This is a
sentence
Try using the method String.lastIndexOf in combination with String.substring.
String listOfWords = "This is a sentence";
String allButLast = listOfWords.substring(0, listOfWords.lastIndexOf(" "));
I added one line to your code. Nothing was removed here.
String listOfWords = "This is a sentence";
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];
String rest = listOfWords.substring(0, listOfWords.indexOf(lastWord)).trim(); // Added
System.out.println(rest);
This will suit your needs:
.split("\\s+[^\\s]+$|\\s+")
For example:
"This is a sentence".split("\\s+[^\\s]+$|\\s+");
Returns:
[This, is, a]
public class StringArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String sentence = "this is a sentence";
int index = sentence.lastIndexOf(" ");
System.out.println(sentence.substring(0, index));
}
}

how to process string in java

I want to make strings like "a b c" to "prefix_a prefix_b prefix_c"
how to do that in java?
You can use the String method: replaceAll(String regex,String replacement)
String s = "a xyz c";
s = s.replaceAll("(\\w+)", "prefix_$1");
System.out.println(s);
You may need to tweek the regexp to meet your exact requirements.
Assuming a split character of a space (" "), the String can be split using the split method, then each new String can have the prefix_ appended, then concatenated back to a String:
String[] tokens = "a b c".split(" ");
String result = "";
for (String token : tokens) {
result += ("prefix_" + token + " ");
}
System.out.println(result);
Output:
prefix_a prefix_b prefix_c
Using a StringBuilder would improve performance if necessary:
String[] tokens = "a b c".split(" ");
StringBuilder result = new StringBuilder();
for (String token : tokens) {
result.append("prefix_");
result.append(token);
result.append(" ");
}
result.deleteCharAt(result.length() - 1);
System.out.println(result.toString());
The only catch with the first sample is that there will be an extraneous space at the end of the last token.
hope I'm not mis-reading the question. Are you just looking for straight up concatenation?
String someString = "a";
String yourPrefix = "prefix_"; // or whatever
String result = yourPrefix + someString;
System.out.println(result);
would show you
prefix_a
You can use StringTokenizer to enumerate over your string, with a "space" delimiter, and in your loop you can add your prefix onto the current element in your enumeration. Bottom line: See StringTokenizer in the javadocs.
You could also do it with regex and a word boundary ("\b"), but this seems brittle.
Another possibility is using String.split to convert your string into an array of strings, and then loop over your array of "a", "b", and "c" and prefix your array elements with the prefix of your choice.
You can split a string using regular expressions and put it back together with a loop over the resulting array:
public class Test {
public static void main (String args[]) {
String s = "a b c";
String[] s2 = s.split("\\s+");
String s3 = "";
if (s2.length > 0)
s3 = "pattern_" + s2[0];
for (int i = 1; i < s2.length; i++) {
s3 = s3 + " pattern_" + s2[i];
}
System.out.println (s3);
}
}
This is C# but should easily translate to Java (but it's not a very smart solution).
String input = "a b c";
String output (" " + input).Replace(" ", "prefix_")
UPDATE
The first solution has no spaces in the output. This solution requires a place holder symbol (#) not occuring in the input.
String output = ("#" + input.Replace(" ", " #")).Replace("#", "prefix_");
It's probably more efficient to use a StringBuilder.
String input = "a b c";
String[] items = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (String item in items)
{
sb.Append("prefix_");
sb.Append(item);
sb.Append(" ");
}
sb.Length--;
String output = sb.ToString();

Categories

Resources