This question already has answers here:
Java. Splitting a multiple word string into two word strings every space [closed]
(2 answers)
Closed 9 years ago.
I have
String input = "one two three four five six seven";
Is there a regex that works with String.split() to grab (up to) two words at a time, such that:
String[] pairs = input.split("some regex");
System.out.println(Arrays.toString(pairs));
results in this:
[one two,two three, three four,four five,five six,six seven]
String[] elements = input.split(" ");
List<String> pairs = new ArrayList<>();
for (int i = 0; i < elements.length - 1; i++) {
pairs.add(elements[i] + " " + elements[i + 1]);
}
No. With String.split(), the things you get out can't overlap.
e.g. you can get: "one two three four" -> {"one","two","three","four"}, but not {"one two","two three", "three four"}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I am trying to make a method that takes in an ArrayList and a letter. If the words in the arraylist start with that letter, than it will be put into a new array of words that start with that letter. For example, an arraylist with ("Apple", "Anny", "Bob") and a letter of "A" would create a new arraylist ("Apple", "Anny"). I am not allowed to use .startsWith(char ch)
public ArrayList<String> wordsThatStartWith(ArrayList<String> words, String letter)
{
ArrayList<String> newWords = new ArrayList<String>();
for(int i = 0; i < words.size(); i++){
if((words.get(i)).substring(i, i + 1) == letter){
newWords.add(words.get(i));
}
}
return newWords;
}
I am not sure why it will not add into a new ArrayList.
Replace
if((words.get(i)).substring(i, i + 1) == letter)
with
if((words.get(i)).substring(0, 1).equalsIgnoreCase(letter))
as you need to get just the first character from the string.
Using the enhanced for loop, you can write it as
for(String word: words) {
if(word.substring(0, 1).equalsIgnoreCase(letter)){
newWords.add(word);
}
}
This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 6 years ago.
I have below mentioned string
String str = "\nArticle\n\nArticle\nArticle";
I want total number of count. How can i get this?
As the string contain \n so always it gives 1 instead of 3
To get you started, I will show you a simple example:
String str = "\nArticle\n\nArticle\nArticle";
// Split the String by \n
String[] words = str.split("\n");
// Keep the count of words
int wordCount = 0;
for(String word : words){
// Only count non-empty Strings
if(!word.isEmpty()) {
wordCount++;
}
}
// Check, answer is 3
System.out.println(wordCount);
This question already has answers here:
Calculating frequency of each word in a sentence in java
(20 answers)
Closed 8 years ago.
I have read in two txt files with words.
Now I was wondering how to calculate the frequency distribution of these two Strings. My idea is to put them into an array and split them by ;. However, how to calculated the frequency distribution?
I appreciate your reply!
Sample code is something like this:
String str1 = "java;python;javascript;programming;Hello;World;Hello";
String str2 = "java;python;javascript;programming;Hello;World;Hello";
List<String> list = new ArrayList<String>();
list.addAll(Arrays.asList(str1.split(";")));
list.addAll(Arrays.asList(str2.split(";")));
for (String word : list)
System.out.println(word + " --> " + Collections.frequency(list,word));
This question already has answers here:
split file sentences into words
(4 answers)
Closed 10 years ago.
How to split an array of sentences into an array of array of words?
If i can split the sentence using split() ..but it's used only single array.
but I need to do multiple array..
Eg:
sentences[0]="one sentence"
sentences[1]=" one sen...."
I need to split like this...
word[0][0]="one word" //first row first word
word[0][1]="second word"
word[0][2]="third word"
word[1][0]="..."//second row first word**
any one can help me.
Try something like this..
for(i=0;i<someLength;i++){
word[i] = sentence[i].split("yourDelimiter");
}
String[] sentences = ...
String[][] words = new String[sentences.length][];
for(int i = 0; i < sentences.length; i++)
{
words[i] = sentences[i].split("\\s+");
}
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?
String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
Looks like homework. So these steps you can follow:
Trim both strings
Convert both strings into ArrayList using space separator
Sort both arrays numerically
Compare both arrays
You can use Scanner.nextInt() to read numbers from the string, add them to a Set, and see if set1.equals(set2) is true.
I would not perform the comparison on the raw strings. Instead, first convert each String to a List<Integer> using String.split() and Integer.parseInt() on each result. Then sort() the lists into ascending order, and then it becomes very easy to compare them.
Try like this.
String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
Set<String> a = new HashSet<String> (Arrays.asList(one.trim().replaceAll("\\s*"," ").split(" ")));
Set<String> b = new HashSet<String> (Arrays.asList(two.trim().replaceAll("\\s*"," ").split(" ")));
boolean ret = (a.size() == b.size()) && a.containsAll(b);
You could tokenize/split the strings based on the spaces, then loop through the resulting tokens which would be the numbers themselves.
You split the strings on whitespace (using either String.split or StringTokenizer) and then convert each of the tokens into a number. Place all the numbers in string one into a HashSet. Do the same for string two. Now all you have to do is to check whether each entry in the first HashSet also occurs in the second one.
I would at first parse numbers as integers, put them to the set and compare them:
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class StringsCompare {
private static String one = "1 2 3 4 5 6";
private static String two = " 3 2 1 5 6 4 ";
public static void main(String[] args) {
StringsCompare sc = new StringsCompare();
System.out.println(sc.compare(one, two));
}
private boolean compare(String one, String two) {
SortedSet<Integer> setOne = getSet(one);
SortedSet<Integer> setTwo = getSet(two);
return setOne.equals(setTwo);
}
private SortedSet<Integer> getSet(String str) {
SortedSet<Integer> result = new TreeSet<Integer>();
StringTokenizer st = new StringTokenizer(str, " ");
while (st.hasMoreTokens()) {
result.add(Integer.valueOf(st.nextToken()));
}
return result;
}
}
Try to parse the strings in int.
Integer.parseInt(One).intValue() == Integer.parseInt(two).intValue()
I'm not sure what you're trying to do but my guess is that you'd better to use arrays.