I have string like "abc /123 /456" and I want to split it into two stings: "abc 123" and "abc 456".
I tried:
String[] str = MESSAGE.split("/")
But didn't provide required result. Could anyone, please, share any ideas with me how to perform it?
Just stick the pieces together in any way you need, like this:
String[] str = MESSAGE.split(" /");
String s1 = str[0] + " " + str[1];
String s2 = str[0] + " " + str[2];
Also notice that it'd be better to split the string using as pattern " /", that is, with a space before the slash.
you did just fine when deciding to split it , after that you should concat the first element of the splited array with all the other elements to achieve what you want.
here's some code to make it clearer.
public class main {
public static void main(String[] args) {
String MESSAGE = "abc /123 /456";
String[] str = MESSAGE.split("/") ;
String[] str2 = new String[str.length-1];
System.out.println(str[0]);
for ( int i=1 ; i<str.length ; i++) {
str2[i-1] = str[0]+str[i];
}
for ( int i=0 ; i<str2.length ; i++) {
System.out.println(str2[i]);
}
}
}
You will need to add a little logic after splitting the String.
This is how I would do it:
String s = "abc /123 /456";
String[] partsOfS = s.split("/");
String prefix = partsOfS[0];
for (int i = 1; i < partsOfS.length; i++) {
System.out.println(prefix + partsOfS[i]);
}
EDIT
For the case of the prefix not separated by / from the other parts of the String but only by space, you will probably need a second split and a second loop, like this:
String s = "abc 123/ 456/";
String[] splitBySpace = s.split(" ");
String prefix = splitBySpace[0];
String[] partsOfS = new String[splitBySpace.length - 1];
for (int i = 1; i < splitBySpace.length; i++) {
partsOfS[i - 1] = splitBySpace[i].replace("/", "");
}
for (int i = 0; i < partsOfS.length; i++) {
System.out.println(prefix + " " + partsOfS[i]);
}
There may be better solutions concerning performance and programming style, but this is working with your example String from the comment.
Related
My task is splitting a string, which starts with numbers and contains numbers and letters, into two sub-strings.The first one consists of all numbers before the first letter. The second one is the remained part, and shouldn't be split even if it contains numbers.
For example, a string "123abc34de" should be split as: "123" and "abc34de".
I know how to write a regular expression for such a string, and it might look like this:
[0-9]{1,}[a-zA-Z]{1,}[a-zA-Z0-9]{0,}
I have tried multiple times but still don't know how to apply regex in String.split() method, and it seems very few online materials about this. Thanks for any help.
you can do it in this way
final String regex = "([0-9]{1,})([a-zA-Z]{1,}[a-zA-Z0-9]{0,})";
final String string = "123ahaha1234";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
matcher.group(1) contains the first part and matcher.group(2) contains the second
you can add it to a list/array using these values
You can use a pretty simple pattern : "^(\\d+)(\\w+)" which capture digits as start, and then when letters appear it take word-char
String string = "123abc34de";
Matcher matcher = Pattern.compile("^(\\d+)(\\w+)").matcher(string);
String firstpart = "";
String secondPart = "";
if (matcher.find()) {
firstpart = matcher.group(1);
secondPart = matcher.group(2);
}
System.out.println(firstpart + " - " + secondPart); // 123 - abc34de
This is not the correct way but u will get the result
public static void main(String[] args) {
String example = "1234abc123";
int index = 0;
String[] arr = new String[example.length()];
for (int i = 0; i < example.length(); i++) {
arr = example.split("");
try{
if(Integer.parseInt(arr[i]) >= 0 & Integer.parseInt(arr[i]) <= 9){
index = i;
}
else
break;
}catch (NumberFormatException e) {
index = index;
}
}
String firstHalf = example.substring(0,Integer.parseInt(arr[index])+1);
String secondHalf = example.substring(Integer.parseInt(arr[index])+1,example.length());
System.out.println(firstHalf);
System.out.println(secondHalf);
}
Output will be: 1234 and in next line abc123
I have my string defined as
text1:text2:text3:text4:text5
I want to get output as
text1:text2:text3
using String methods.
I have tried using lastIndexOf, then substring and then again lastIndexOf.
I want to avoid these three steps with calling lastIndexOf two times.
Is there a better way to achieve this?
You can do this by running a loop to iterate over the characters of the string from index = 0 to index = lastIndexOf('3'). Here's the code:
String s = "text1:text2:text3:text4:text5";
for(int i = 0; i < = s.lastIndexOf('3'); i++)
System.out.print(s.charAt(i));
This gives you the required output.
OUTPUT:
text1:text2:text3
A regular expression could be used to identify the correct part of the string:
private static Pattern PATTERN = Pattern.compile("([^:]*:){2}[^:]*(?=:|$)");
public static String find(String input) {
Matcher m = PATTERN.matcher(input);
return m.find() ? m.group() : null;
}
Alternatively do not use substring between every call of lastIndexOf, but use the version of lastIndexOf that restricts the index range:
public static String find(String input, int colonCount) {
int lastIndex = input.length();
while (colonCount > 0) {
lastIndex = input.lastIndexOf(':', lastIndex-1);
colonCount--;
}
return lastIndex >= 0 ? input.substring(0, lastIndex) : null;
}
Note that here colonCount is the number of : that are left out of the string.
You could try:
String test = "text1:text2:text3:text4:text5";
String splitted = text.split(":")
String result = "";
for (int i = 0; i <3; i++) {
result += splitted[i] + ":"
}
result = result.substring(0, result.length() -1)
You can use the Java split()-method:
String string = "text1:text2:text3:text4:text5";
String[] text = string.split(":");
String text1 = text[0];
String text2 = text[1];
String text3 = text[2];
And then generate the output directly or with a for-loop:
// directly
System.out.println(text1 + ":" + text2 + ":" + text3);
// for-loop. Just enter, how many elements you want to display.
for(int i = 0; i < 3; i++){
System.out.println(text[i] + " ");
}
Output:
text1 text2 text3
The advantage of using this method is, that your input and output can be a bit more complex, because you have power over the order in which the words can be printed.
Example:
Consider Master Yoda.
He has a strange way of talking and often mixes up the sentence structure. When he introduces himself, he says the (incorrect!) senctence: "Master Yoda my name is".
Now, you want to create an universal translator, that - of course - fixes those mistakes while translating from one species to another.
You take in the input-string and "divide" it into its parts:
String string = "Master:Yoda:my:name:is"
String[] text = string.split(":");
String jediTitle = text[0];
String lastName = text[1];
String posessivePronoun = text[2];
String noun = text[3];
String linkingVerb = text[4];
The array "text" now contains the sentence in the order that you put it in. Now your translator can analyze the structure and correct it:
String correctSentenceStructure = posessivePronoun + " " + noun + " " + linkingVerb + " " + jediTitle + " " + lastName;
System.out.println(correctSentenceStructure);
Output:
"My name is Master Yoda"
A working translator might be another step towards piece in the galaxy.
Maby try this one-line s.substring(0, s.lastIndexOf('3')+1);
Complete example:
package testing.project;
public class Main {
public static void main(String[] args) {
String s = "text1:text2:text3:text4:text5";
System.out.println(s.substring(0, s.lastIndexOf('3')+1));
}
}
Output:
text1:text2:text3
I'm trying to make an encryptor.What i want it to do:
Get the text i enter and reverse the first two letters of every word
and then display it again.
I have tried a lot of ways.This is the last one i've tried:
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
Display.appendText(swappedString + " ");
}
}
You may want to consider maintaining all the delimiters lost from the first String.split("\\W+") so they can be included in the final result. I would do that with a String.split("\\w+")
You may also want to consider that when you swap the first two letters, if the first letter is capital it becomes lowercase and the second letter becomes uppercase. Otherwise, just do a direct swap.
Code sample:
public static void main(String[] args) throws Exception {
String data = "Hello;World! My name is John. I write code.";
String[] words = data.split("\\W+");
String[] delimiters = data.split("\\w+");
int delimiterIndex = 0;
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word.length() < 2) {
sb.append(word);
} else {
char firstLetter = word.charAt(0);
char secondLetter = word.charAt(1);
if (Character.isUpperCase(firstLetter)) {
// Swap the first two letters and change casing
sb.append(Character.toUpperCase(secondLetter))
.append(Character.toLowerCase(firstLetter));
} else {
// Swap the first two letters
sb.append(secondLetter)
.append(firstLetter);
}
// Append the rest of the word past the first two letters
sb.append(word.substring(2));
}
// Append delimiters
if (delimiterIndex < delimiters.length) {
// Skip blank delimiters if there are any
while (delimiters[delimiterIndex].isEmpty()) {
delimiterIndex++;
}
// Append delimiter
sb.append(delimiters[delimiterIndex++]);
}
}
data = sb.toString();
// Display result
System.out.println(data);
}
Results:
Ehllo;Owrld! Ym anme si Ojhn. I rwite ocde.
public class Encrypto {
public static void main(String[] args) {
String input="Hello World";
String [] word = input.split(" ");
// System.out.println(word[0]);
String encryWord="";
for(int i=0;i<word.length;i++){
if (word[i].length() > 0) {
String tmp0 = String.valueOf(word[i].charAt(1));
String tmp1 = String.valueOf(word[i].charAt(0));
encryWord += tmp0.toLowerCase() + tmp1.toLowerCase() + word[i].substring(2) + " ";
}else{
encryWord +=word[i];
}
}
System.out.println(encryWord);
}
}
I think answer is more helpful for you
There are a few problems.
Declare zz outside the loop if you want to use it outside.
Append zz on every iteration. Not just assign it.
Something like this,
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String zz = "";
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
String b= " ";
zz += swappedString + b;
}
Display.setText(zz + " ");
}
You are splitting with non-word (\W+) characters, but replacing it only with a space " ". This could alter the string with special characters.
Not sure what exactly you are looking for but i little modification in your code see if this suits your needs
String storage = "Test test t";
String[] arr = storage.split("\\W+");
String abc = "";
for ( String ss : arr) {
if(ss.length() > 1)
{
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String( c );
String b = " ";
String zz = swappedString + b;
abc = abc + zz;
}else{
abc = abc + ss;
}
}
System.out.println(abc);
In Java strings are immutable. You can't modify them "on the fly", you need to reassign them to a new instance.
Additionally, you are setting the last display text to zz, but zz is a local variable to your loop, and therefore it gets re-instantiated with every iteration. In other words, you would be assigning to display only the last word!
Here is what you have to do to make it work:
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String[] newText = new String[arr.length];
for ( int i = 0; i<arr.length; i++) {
String original = arr[i];
String modified = ((char) original.charAt(1)) + ((char) original.charAt(0)) + original.substring(2);
newText[i] = modified;
}
//Join with spaces
String modifiedText = Arrays.asList(newText).stream().collect(Collectors.join(" "));
Display.setText(modifiedText);
Note that:
1) We are assuming all strings have at least 2 chars
2) that your splitting logic is correct. Can you think some edge cases where your regexp fails?
I have string like "align is going to school sad may me". I want to get the sub string after the four spaces. The String will be entered at run time. can anyone suggest me to find the Sub String after some set of spaces......
String st = "align is going to school sad may me";
int i = 0;
String [] strings = new String [15];
StringTokenizer stringTokenizer = new StringTokenizer (st, " ");
while (stringTokenizer.hasMoreElements ())
{
strings [i]= (String)stringTokenizer.nextElement ();
i++;
}
System.out.println ("I value is" + i);
for (int j=4; j<i; j++)
{
System.out.print (strings[j] + " ");
}
I've tried this one and it's working can you please suggest me simple method to find the Sub string after some set of spaces.
st = st.replaceAll("^(\\S*\\s){4}", "");
^ indicates that we remove only from the first character of the string.
\s is any white space. It would also remove, for example, tabulations.
\S is any non white space character.
* means any number of occurrences of the character.
So, \S* is any number of non white space characters before the white space.
{4} is obviously because you want to remove 4 white spaces.
You could also use:
st = st.replaceFirst("(\\S*\\s){4}", "");
which is the same but you don't need the ^.
In case the input string could have less than 4 white spaces:
st = st.replaceAll("^(\\S*\\s){1,4}", "");
would return you the last word of the string, only if the string doesn't end on a white space. You can be sure of that if you call trim first:
st = st.trim().replaceAll("^(\\S*\\s){1,4}", "");
What about using split?
st.split (" ", 5) [4]
It splits string by spaces, into not more than 5 chunks. Last chunk (with index 4) will contain everything after fourth space.
If it is not guaranteed that string contains 4 spaces, additional check is required:
String [] chunks = st.split (" ", 5);
String tail = chunks.length == 5 ? chunks [4] : null;
Tail will contain everything after fourth space or null, is there are less than four spaces in original string.
public static void main(String[] args) {
String st = " align is going to school sad may me ";
String trim = st.trim(); // if given string have space before and after string.
String[] splitted = trim.split("\\s+");// split the string into words.
String substring = "";
if (splitted.length >= 4) { // checks the condition
for (int i = 4; i < splitted.length; i++)
substring = substring + splitted[i] + " ";
}
System.out.println(substring);
}
This may be a overkill but it uses simple string operations (just str.indexOf(' ')).
If you needed for a school project or someting:
String str ="ada adasd dasdsa d adasdad dasasd";
int targetMatch = 4;
int offset = 0;
for(int i = 0 ; i < targetMatch; i++){
int position = str.indexOf(' ', offset);
if(position != -1){
System.out.println("position: "+ position);
offset = position+1;
}
}
String result = str.substring(offset);
System.out.println(result);
For real project... advanced regex would be better.
Here's a trivial and simple implementation that solves your problem:
String s = "I've tried this one and it's working can you please suggest";
int index = -1;
for (int i = 0; i < 4; i++) {
index = s.indexOf(' ', index + 1);
}
System.out.println(s.substring(index + 1));
It will fail if the string starts with a space or if it contains sequences of spaces. But it's a start.
Output: and it's working can you please suggest
public class MySplit {
public static void main(String agsp[]) {
String oldString = "roma h totti milan kaka juve love";
String[] allStrings = oldString.split("\\s");
String newString = "";
for (int i = 3; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
System.out.println(newString);
}
}
you can also make function like this
public String newSplit(String data, int index){
String[] allStrings = data.split("\\s");
String newString = "";
for (int i = index; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
return newString
}
The simple way using this piece of code
String thisString="Hello world go to kashmir";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
String first = parts[3];//"hello"
String second = parts[4];//"World"
How can I divide a sentence like "He and his brother playing football." into few part like "He and", "and his", "his brother", "brother playing" and "playing football" . Is it possible to do that by using Java?
Assuming the "words" are always separated by a single space. Use String.split()
String[] words = "He and his brother playing football.".split("\\s+");
for (int i = 0, l = words.length; i + 1 < l; i++)
System.out.println(words[i] + " " + words[i + 1]);
You can do it using BreakIterator class and its static method getSentenceInstance().
It Returns a new BreakIterator instance for sentence breaks for the default locale.
You can also use getWordInstance(), getLineInstance().. to break words, line...etc
eg:
BreakIterator boundary = BreakIterator.getSentenceInstance();
boundary.setText("Your_Sentence");
int start = boundary.first();
int end = boundary.next();
Iterate over it... to get the Sentences....
For more detail look at this link:
http://docs.oracle.com/javase/6/docs/api/java/text/BreakIterator.html
Edited Answer: This is a working code
String sent = "My name is vivek. I work in TaxSmart";
BreakIterator bi = BreakIterator.getSentenceInstance();
bi.setText(sent);
int index = 0;
while (bi.next() != BreakIterator.DONE) {
String sentence = sent.substring(index, bi.current());
System.out.println("Sentence: " + sentence);
index = bi.current();
}
String str="He and his brother playing football";
String [] strArray=str.split(" ");
for(int i=0;i<strArray.length-1 ;i++)
{
System.out.println(strArray[i]+" "+strArray[i+1]);
}
Use a StringTokenizer to separate by spaces or other characters.
import java.util.StringTokenizer;
public class Test {
private static String[] tokenize(String str) {
StringTokenizer tokenizer = new StringTokenizer(str);
String[] arr = new String[tokenizer.countTokens()];
int i = 0;
while (tokenizer.hasMoreTokens()) {
arr[i++] = tokenizer.nextToken();
}
return arr;
}
public static void main(String[] args) {
String[] strs = tokenize("Sandy sells seashells by the sea shore.");
for (String s : strs)
System.out.println(s);
}
}
Should print out:
Sandy
sells
seashells
by
the
sea
shore.
May or may not be what you're after.