How can I split a string in to multiple parts? - java

I have a string with several words separated by spaces, e.g. "firstword second third", and an ArrayList. I want to split the string into several pieces, and add the 'piece' strings to the ArrayList.
For example,"firstword second third" can be split to three separate strings , so the ArrayList would have 3 elements; "1 2 3 4" can be split into 4 strings, in 4 elements of the ArrayList. See the code below:
public void separateAndAdd(String notseparated) {
for(int i=0;i<canBeSepartedinto(notseparated);i++{
//what should i put here in order to split the string via spaces?
thearray.add(separatedstring);
}
}
public int canBeSeparatedinto(String string)
//what do i put here to find out the amount of spaces inside the string?
return ....
}
Please leave a comment if you dont get what I mean or I should fix some errors in this post. Thanks for your time!

You can split the String at the spaces using split():
String[] parts = inputString.split(" ");
Afterwards iterate over the array and add the individual parts (if !"".equals(parts[i]) to the list.

If you want to split on one space, you can use .split(" ");. If you want to split on all spaces in a row, use .split(" +");.
Consider the following example:
class SplitTest {
public static void main(String...args) {
String s = "This is a test"; // note two spaces between 'a' and 'test'
String[] a = s.split(" ");
String[] b = s.split(" +");
System.out.println("a: " + a.length);
for(int i = 0; i < a.length; i++) {
System.out.println("i " + a[i]);
}
System.out.println("b: " + b.length);
for(int i = 0; i < b.length; i++) {
System.out.println("i " + b[i]);
}
}
}
If you are worried about non-standard spaces, you can use "\\s+" instead of " +", as "\\s" will capture any white space, not just the 'space character'.
So your separate and add method becomes:
void separateAndAdd(String raw) {
String[] tokens = raw.split("\\s+");
theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
for(String s : tokens) {
theArray.add(s);
}
}
Here's a more complete example - note that there is a small modification in the separateAndAdd method that I discovered during testing.
import java.util.*;
class SplitTest {
public static void main(String...args) {
SplitTest st = new SplitTest();
st.separateAndAdd("This is a test");
st.separateAndAdd("of the emergency");
st.separateAndAdd("");
st.separateAndAdd("broadcast system.");
System.out.println(st);
}
ArrayList<String> theArray = new ArrayList<String>();
void separateAndAdd(String raw) {
String[] tokens = raw.split("\\s+");
theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
for(String s : tokens) {
if(!s.isEmpty()) theArray.add(s);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for(String s : theArray)
sb.append(s).append(" ");
return sb.toString().trim();
}
}

I would suggest using the
apache.commons.lang.StringUtils library.
It is the easiest and covers all the different conditions you can want int he spliting up of a string with minimum code.
Here is a reference to the split method :
Split Method
you can also refer to the other options available for the split method on the same link.

Do this:
thearray = new ArrayList<String>(Arrays.asList(notseparated.split(" ")));
or if thearray already instantiated
thearray.addAll(Arrays.asList(notseparated.split(" ")));

If you want to split the string in different parts, like here i am going to show you that how i can split this string 14-03-2016 in day,month and year.
String[] parts = myDate.split("-");
day=parts[0];
month=parts[1];
year=parts[2];

You can do that using .split() try this
String[] words= inputString.split("\\s");

try this:
string to 2 part:
public String[] get(String s){
int l = s.length();
int t = l / 2;
String first = "";
String sec = "";
for(int i =0; i<l; i++){
if(i < t){
first += s.charAt(i);
}else{
sec += s.charAt(i);
}
}
String[] result = {first, sec};
return result;
}
example:
String s = "HelloWorld";
String[] res = get(s);
System.out.println(res[0]+" "+res[1])
output:
Hello World

Related

Reverse Odd-length Words in the given String in Java

I expect the User to provide a sentence.
And as an output, they will reverse a string with only the odd-length words reversed (i.e. even-length words should remain intact).
static String secretAgentII(String s) {
StringBuffer sb = new StringBuffer();
String[] newStr = s.split(" ");
String result = "";
for (int i = 0; i < newStr.length; i++) {
if (newStr[i].length() % 2 != 0) {
sb.append(newStr[i]).reverse();
result += sb + " ";
}
result += newStr[i] + " ";
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(secretAgentII(s));
}
Input:
One two three Four
Expected Output:
enO owT eerhT Four
The actual Output:
enO One owtOne two eerhtenOtwo three Four
How can I fix that?
I went ahead and wrote a method for what I think you are asking for.
public static String secretAgentII(String input){
StringBuilder returnValue = new StringBuilder();
input = input.replaceAll(" +", " ");
String[] tempArray = input.split(" ");
for (int i = 0; i < tempArray.length; i++) {
String currentString = tempArray[i];
if (currentString.length() % 2 == 1) {
char[] tempArrayOfStringChars = currentString.toCharArray();
for (int j = tempArrayOfStringChars.length - 1; j >= 0; j--) {
returnValue.append(tempArrayOfStringChars[j]);
}
} else {
returnValue.append(currentString);
}
if (i != tempArray.length - 1) { //This prevents a leading space at the end of your string
returnValue.append(' ');
}
}
return returnValue.toString();
}
From what I could tell, you only want the words of odd length to be reversed.
My sample input and output was as follows.
Input: One two three four five six seven eight nine ten
Output: enO owt eerht four five xis neves thgie nine net
Your problem is that you add to result the whole sb, instead of just the current reverse word. Meaning you need to "reset" (create a new) StringBurrer for each iteration.
You're also missing the else where you want to preserve the correct word's order
for (int i = 0; i < newStr.length; i++) {
if (newStr[i].length() % 2 == 1) {
StringBuffer sb = new StringBuffer();
sb.append(newStr[i]);
result += sb.reverse() + " ";
}
else {
result += newStr[i] + " ";
}
}
In your method secretAgentII the StringBuffer should have no other values so that it would not be concatenated to other strings.
I placed sb.replace(0, newStr[i].length(), newStr[i]).reverse(); inside the for loop so that it would replace the existing string in every use.
I also placed an else before the line result += newStr[i] + " "; for the original string doesn't need to be concatenated when it is reversed.
static String secretAgentII(String s) {
StringBuffer sb = new StringBuffer();
String[] newStr = s.split(" ");
String result = "";
for (int i = 0; i < newStr.length; i++) {
if (newStr[i].length() % 2 != 0) {
sb.replace(0, newStr[i].length(), newStr[i]).reverse();
result += sb + " ";
} else
result += newStr[i] + " ";
}
return result;
}
Input: One Two Three Four
Output: enO owT eerhT Four
note: you are using too many spaces, try researching Java conventions on writing code.
StringBuilder + StringJoiner
Never use plain string concatenation the loop because in Java Strings are immutable. That means every s1 + s2 produces new intermediate string, which don't need (since only the end result would be used). Concatenation in the loop effects performance and increase memory allocation.
Therefore, it's highly advisable to use StringBuilder, or other built-in mechanisms like static method String.join(), StringJoiner or Collector joining() when you need to combine multiple strings together.
To avoid bother about adding a white space after each word ourself, we can make use of the StringJoiner. Through its parameterized constructor we can provide the required delimiter " ".
That's how it might be implemented:
public static String reverseOdd1(String str) {
StringJoiner result = new StringJoiner(" ");
String[] words = str.split(" ");
for (String word : words) {
if (word.length() % 2 != 0) result.add(new StringBuilder(word).reverse());
else result.add(word);
}
return result.toString();
}
Note that it's not advisable to use StringBuffer in single-threaded environment because its methods are synchronized to make it tread-safe (and synchronization doesn't come for free), and instead use it sibling StringBuilder which has the same methods.
Here's a couple of more advanced solutions.
Stream IPA - Collectors.joining()
You can generate a Stream of words, revers odd-length words using map() operation, and generate the resulting string using Collector joining().
public static String reverseOdd2(String str) {
return Arrays.stream(str.split(" "))
.map(s -> s.length() % 2 == 0 ? s : new StringBuilder(s).reverse().toString())
.collect(Collectors.joining(" "));
}
Regex - Matcher.replaceAll()
Another option is to use regular expressions.
To capture a separate word we can use the following pattern:
public static final Pattern WORD = Pattern.compile("\\b(\\w+)\\b");
Where \\b is a so-called boundary matcher denoting a word boundary (for more information, refer to the documentation).
We can create a Matcher instance using this patter and the given string and make use of the Java 9 method Matcher.replaceAll() to generate the resulting string.
public static String reverseOdd3(String str) {
return WORD.matcher(str).replaceAll(matchResult -> {
String group = matchResult.group(1);
return group.length() % 2 == 0 ? group : new StringBuilder(group).reverse().toString();
});
}
Usage Example
main
public static void main(String[] args) {
System.out.println(reverseOdd1("One Two Three Four"));
System.out.println(reverseOdd2("One Two Three Four"));
System.out.println(reverseOdd3("One Two Three Four"));
}
Output:
enO owT eerhT Four
enO owT eerhT Four
enO owT eerhT Four

Replacing specific words in a string, given an arraylist of an index of where the words are

I have these two methods, one "findFour" finds the index of all the "bad words" in a given string. It puts the index of the located bad words into an arrayList and returns it. The next method "replaceFour" will find those same bad words in the same given string, and then replace those words with some symbol like "$$$$" and return the String. For example, if my input String was "Oh dang that's crap", then the findFour method would return an arrayList with [3, 13] (which is the index of the two "bad" words), then the replaceFour method would return "Oh $$$$ that's $$$$" I am trying to figure out how to basically make the replaceFour method.
public ArrayList<Integer> findFour(String text){
for(int i=0; i<text.length()-4;i++){
String fourLetter = text.substring(i, i+4);
FourWords.add(fourLetter);
if(fourLetter.equals(BadWords.get(0)) || fourLetter.equals(BadWords.get(1)) || fourLetter.equals(BadWords.get(2))){
IndexofBad.add(i);
}
}
return IndexofBad; //this arrayList contains index of all the bad words in the given string
}
//have to replace the bad words with a different text
public void replaceFour(String text){//Have not figured out
newString.equals(text);
for(int i=0; i<IndexofBad.size(); i++){
}
}
use String.replace (Oracle doc)
You can do it using basic String manipulation, like using indexOf() and substring() methods.
String s = "Oh crap that sucks";
List<Integer> badWordIndices = List.of(3, 13);
for (Integer i : badWordIndices) {
int indexOfNextSpace = s.indexOf(" ", i);
s = s.substring(0, i) + "$$$$" + (indexOfNextSpace != -1 ? s.substring(indexOfNextSpace) : "");
}
System.out.println(s);
Output
Oh $$$$ that $$$$
Try this solution with List..
static List<String> badWords = null;
public static String replaceBadWords(String s) {
List<String> lsStr = Arrays.asList(s.split(" "));
List<String> result = new ArrayList<String>();
for(String sr: lsStr) {
if(badWords.contains(sr)) {
sr = "$$$";
}
result.add(sr);
}
return String.join(" ", result);
}
public static void main(String[] args) {
badWords = new ArrayList<>();
badWords.add("crap");
badWords.add("dang");
System.out.println(replaceBadWords("Oh dang that's crap"));
}

Convert array of Strings to String

Hello i have a little problem with array conversion
i want to convert this array format ["x","z","y"] To this String Format ('x','y','z') with commas and parentheses.
btw this array is dynamic in size may be increased or decreased
this is my try
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String [] arr = {"x","y","z"};
String s = "(";
for(int i = 0; i <arr.length;i++){
s +="'".concat(arr[i]).concat("'") + ',' ;
if(i == arr.length-1)
s.replace(',', ')');
}
System.out.print(s);
}
this is my output ('x','y','z',
i want to replace the last comma with ')'
This also will do the magic..
Please use StringBuilder for these kind of string operations..
for (int i = 0; i < arr.length; i++) {
s += "'".concat(arr[i]).concat("'") + ',';
}
s = s.concat(")");
System.out.print(s.replace(",)", ")"));
s.replace(',', ')');
Here you are trying to replace the comma, but Strings in java are immutable, it means you are in fact replacing this, but not assigning the value to any variable, so it's pointless. Also, that replace will not do what you think. Instead, you need to:
s = s.substring(0, s.length()-1);
This is gonna remove the last character from the String (that is extra comma at the end). Then just append ) to it and you are done.
You can also use the String.join method :
public static void main(String[] args) {
String [] arr = {"x","y","z"};
String s = String.join("','", arr);
s = "('"+s+"')";
System.out.print(s);
}
You can try this, using String.format and String.join
String[] arr = { "x", "y", "z" };
String s = String.format("('%s')", String.join("','", arr));
System.out.println(s);
It print
('x','y','z')
Edit
If you are using jdk7, you can use StringBuilder to avoid performance issues, as shown in the code:
String[] a = { "x", "y", "z" };
StringBuilder b = new StringBuilder("(");
for (int i = 0; i < a.length; i++) {
b.append("'").append(String.valueOf(a[i])).append("'");
b.append((i == a.length - 1) ? ")" : ", ");
}
System.out.println(b);
It print
('x','y','z')

How to write a replaceAll function java?

I'm trying to write a program that will allow a user to input a phrase (for example: "I like cats") and print each word on a separate line. I have already written the part to allow a new line at every space but I don't want to have blank lines between the words because of excess spaces. I can't use any regular expressions such as String.split(), replaceAll() or trim().
I tried using a few different methods but I don't know how to delete spaces if you don't know the exact number there could be. I tried a bunch of different methods but nothing seems to work.
Is there a way I could implement it into the code I've already written?
for (i=0; i<length-1;) {
j = text.indexOf(" ", i);
if (j==-1) {
j = text.length();
}
System.out.print("\n"+text.substring(i,j));
i = j+1;
}
Or how can I write a new expression for it? Any suggestions would really be appreciated.
I have already written the part to allow a new line at every space but
I don't want to have blank lines between the words because of excess
spaces.
If you can't use trim() or replaceAll(), you can use java.util.Scanner to read each word as a token. By default Scanner uses white space pattern as a delimiter for finding tokens. Similarly, you can also use StringTokenizer to print each word on new line.
String str = "I like cats";
Scanner scanner = new Scanner(str);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
OUTPUT
I
like
cats
Here is a simple solution using substring() and indexOf()
public static void main(String[] args) {
List<String> split = split("I like cats");
split.forEach(System.out::println);
}
public static List<String> split(String s){
List<String> list = new ArrayList<>();
while(s.contains(" ")){
int pos = s.indexOf(' ');
list.add(s.substring(0, pos));
s = s.substring(pos + 1);
}
list.add(s);
return list;
}
Edit:
If you only want to print the text without splitting or making lists, you can use this:
public static void main(String[] args) {
newLine("I like cats");
}
public static void newLine(String s){
while(s.contains(" ")){
int pos = s.indexOf(' ');
System.out.println(s.substring(0, pos));
s = s.substring(pos + 1);
}
System.out.println(s);
}
I think this will solve your problem.
public static List<String> getWords(String text) {
List<String> words = new ArrayList<>();
BreakIterator breakIterator = BreakIterator.getWordInstance();
breakIterator.setText(text);
int lastIndex = breakIterator.first();
while (BreakIterator.DONE != lastIndex) {
int firstIndex = lastIndex;
lastIndex = breakIterator.next();
if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(text.charAt(firstIndex))) {
words.add(text.substring(firstIndex, lastIndex));
}
}
return words;
}
public static void main(String[] args) {
String text = "I like cats";
List<String> words = getWords(text);
for (String word : words) {
System.out.println(word);
}
}
Output :
I
like
cats
What about something like this, its O(N) time complexity:
Just use a string builder to create the string as you iterate through your string, add "\n" whenever you find a space
String word = "I like cats";
StringBuilder sb = new StringBuilder();
boolean newLine = true;
for(int i = 0; i < word.length(); i++) {
if (word.charAt(i) == ' ') {
if (newLine) {
sb.append("\n");
newLine = false;
}
} else {
newLine = true;
sb.append(word.charAt(i));
}
}
String result = sb.toString();
EDIT: Fixed the problem mentioned on comments (new line on multiple spaces)
Sorry, I didnot caution you cannot use replaceAll().
This is my other solution:
String s = "I like cats";
Pattern p = Pattern.compile("([\\S])+");
Matcher m = p.matcher(s);
while (m.find( )) {
System.out.println(m.group());
}
Old solution:
String s = "I like cats";
System.out.println(s.replaceAll("( )+","\n"));
You almost done all job. Just make small addition, and your code will work as you wish:
for (int i = 0; i < length - 1;) {
j = text.indexOf(" ", i);
if (i == j) { //if next space after space, skip it
i = j + 1;
continue;
}
if (j == -1) {
j = text.length();
}
System.out.print("\n" + text.substring(i, j));
i = j + 1;
}

Remove characters at certain position at string

I want to remove certain characters at specific positions of the String. I have the positions, but I am facing problems removing the characters.
what i am doing is:
if (string.subSequence(k, k + 4).equals("\n\t\t\t")){
string = string.subSequence(0, k) + "" + s.subSequence(k, s.length());
}
I need to remove "\n\t\t\t" from string
Use StringBuilder:
StringBuilder sb = new StringBuilder(str);
sb.delete(start, end);
sb.deleteCharAt(index);
String result = sb.toString();
Use StringBuilder
String str=" ab a acd";
StringBuilder sb = new StringBuilder(str);
sb.delete(0,3);
sb.deleteCharAt(0);
String result = sb.toString();
System.out.println(result);
public static String remove(int postion, String stringName) {
char [] charArray = stringName.toCharArray();
char [] resultArray = new char[charArray.length];
int count = 0;
for (int i=0; i< charArray.length; i++) {
if (i != postion-1) {
resultArray[count] = charArray[i];
count++;
}
}
return String.valueOf(resultArray);
}
Use String.ReplaceAll() instead of this.
But if you only want to remove specific element only you can use substring().
Now you want to know position which you already know.
Put your points in a HashSet called set
StringBuilder sb=new StringBuilder();
for(int i=0;i<string.length();i++){
if(!set.contains(string.charAt(i)))
sb.append(string.charAt(i));
}
String reformattedString=sb.toString();
First you have to put \ in front of the special characters in order to do the matching of the two string, thus you will have .equals("\"\\n\\t\\t\\t\""), otherwise the substring is not going to be recognized inside the string. Then the other thing which you have to fix is the position of the index begin and end inside .subSequence(k,k+10) since the first and the last character are 10 positions apart and not 4. Note also that when you patch the string you go from position 0 to k and from k+10 to str.length(). If you go from 0 --> k and k --> length() you just join the old string together :).
Your code should work like this, I have tested it already
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length()));
}
also you don't need +" "+ since you are adding strings. Whoever wants to see the effect of this can run this simple code:
public class ReplaceChars_20354310_part2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String str = "This is a weird string containg balndbfhr frfrf br brbfbrf b\"\\n\\t\\t\\t\"";
System.out.println(str); //print str
System.out.println(ReplaceChars(str)); //then print after you replace the substring
System.out.println("\n"); //skip line
String str2 = "Whatever\"\\n\\t\\t\\t\"you want to put here"; //print str
System.out.println(str2); //then print after you replace the substring
System.out.println(ReplaceChars(str2));
}
//Method ReplaceChars
public static String ReplaceChars (String str) {
String newstr ="";
int k;
k = str.indexOf("\"\\n\\t\\t\\t\""); //position were the string starts within the larger string
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length())); //or just str
}
return newstr;
}//end method
}

Categories

Resources