Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can reprint this string
List<String> abc = new ArrayList<String>();
abc.add("D. Bwer");
abc.add("Z. abc");
abc.add("X. RDS");
Output : Bwer, D.
abc, Z.
RDS, X.
tried swapping the indexes but didnt work
List<String> abc = new ArrayList<String>();
abc.add("D. Bwer");
abc.add("Z. abc");
abc.add("X. RDS");
List<String> string1= new ArrayList<String>();
for(String str1: abc){
String new1= str1.split("\\s+")[0];
String new2= str1.split("\\s+")[1];
String temp = new2+","+ new1;
string1.add(temp );
}
}
Try something like this
List<String> abc = new ArrayList<String>();
abc.add("D. Bwer");
abc.add("Z. abc");
abc.add("X. RDS");
for(String i:abc){
String[] arr=i.split(" ");
System.out.println(arr[1]+", "+arr[0]);
}
If you want to go by substring
First solution if space location varies.
Second solution if you know that space will always be present at third location.
List<String> abc = new ArrayList<String>();
abc.add("D. Bwer");
abc.add("Z. abc");
abc.add("X. RDS");
for(String dummy:abc){
System.out.println((dummy.substring(dummy.indexOf(" ")+1))+",
"+dummy.substring(0, dummy.indexOf(" "))); //1
System.out.println(dummy.substring(3)+", "+dummy.substring(0,3)); //2
}
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range.
Collections.swap(arrayList,0,4);
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Basically, I am getting ready for an interview and following a regime that gives me a bunch of challenges that are often thrown in interviews.
This particular challenge's goal is to count the number of words that appear more than once in a sentence excluding punctuations. I did it but it took me at least 5 minutes to come up with it and code it.
I'm not sure if taking 5 minutes is acceptable to code something like this in java interviews so I would like to see something simpler with maybe less code. Below is how I solved it.
System.out.println("Part 6 challenge-------------------------------------------------------------------------");
String sentence3 = "She's the queen and likes, apples APPLES, bananas BANANAS Bananas, and oranges ORANGE."; //original string
StringBuilder sb3 = new StringBuilder(); //declared string builder to build new string without punctuations
char [] punctuations = {'.',',',':','?','!',';'};//Char array containing punctuations to lookout for
for (int i=0; i<sentence3.length(); i++){
boolean p = false; //declared boolean within loop to turn on if punctuation was found in the original string
for (Character c: punctuations){
if (sentence3.charAt(i) == c){
p = true;// turn on
}
} if(!p){
sb3.append(sentence3.charAt(i));//if no punctuations found, add it to the string builder to build new string
}
}
String word[] = sb3.toString().split(" ");
Set<String> uniqueWords = new HashSet<>();
int count = 0;
for (String s: word) {
uniqueWords.add(s.toLowerCase());
}
for (String s: uniqueWords){
for (String w: word){
if (s.equals(w.toLowerCase())){
count++;
}
}
System.out.println(String.format("Found %s %d times", s, count));
count =0;
}
A shorter way, outlined:
Split by regexp;
Filter for words (may be not needed depending on your regexp);
Replace Set<String> with a Map<String, Integer> and count word quantities in linear time;
Filter out and output words with count > 1.
BTW this can all be one stream expression if you're into minimal statement count.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
System.out.println("Please input the elements and seperate each by a comma.");
e = dk.nextLine();
String[] elems = new String[e.length()];
st = new StringTokenizer(e,",");
for (int i = 0; i<e.length(); i++) {
elems[i] = st.nextToken().toString();
}
for (int i=0; i<e.length(); i++){
System.out.println(elems[i]);
}
I am trying to print out the array elems[] but it wont work the error java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:349 seems to be at line:
elems[i] = st.nextToken().toString();
can you help me identify and understand the problem?
A correct version:
String[] elems = e.split(",");
for(String elem : elems) {
System.out.println(elem);
}
The mistake you made is that e.length() returns the size of the string (its number of characters) so you ended up calling st.nextToken() more times than there are actual tokens separated by ",". Hence the exception.
#Jean posted a slim version of what you are trying, but ultimately to help to understand the error
e = dk.nextLine(); // input: Alfredo,Bauer,Cisco
String[] elems = new String[e.length()]; // length is 20
st = new StringTokenizer(e,","); // st has a length of 3
Now if you call it like this
for(int i = 0;i<e.length();i++){
elems[i] = st.nextToken().toString(); // NoSuchElementException
}
Because you try to call the nextToken() which does not exist.
The docs:
Returns the next token from this string tokenizer.
Throws:
NoSuchElementException - if there are no more tokens in this
tokenizer's string.
To fix your problem use the length of countTokens()
OR
while(st.hasMoreElements()){
elems[i] = st.nextToken().toString();
}
Another alternative.
String[] elems = e.split(",");
System.out.print(Arrays.toString(elems ));
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have arraylist of strings that have data of kind like this
{"this","is",is","repeating"}
i need a java code that will give me the element(s) which is least repeating
the output should be
this = 1
repeating = 1
Thanks in advance
This will do the trick, it's a bit long but maybe there's some utils package that does the same (haven't found one so far):
String[] words = {"this", "is", "is", "repeating"};
TreeMap<Integer, List<String>> frequencyMap = new TreeMap<Integer, List<String>>();
for (String word : words) {
Integer frequency = 0;
for (String word2 : words) {
if (word.equals(word2)) {
frequency++;
}
}
if (frequencyMap.containsKey(frequency)) {
List<String> wordsWithFrequency = frequencyMap.get(frequency);
wordsWithFrequency.add(word);
} else {
List<String> wordsWithFrequency = new ArrayList<String>();
wordsWithFrequency.add(word);
frequencyMap.put(frequency, wordsWithFrequency);
}
}
if (frequencyMap.size() > 0) {
List<String> leastFrequentWords = frequencyMap.get(frequencyMap.firstKey());
for (String string : leastFrequentWords) {
System.out.println(string + " = " + frequencyMap.firstKey());
}
}
This prints out:
this = 1
repeating = 1
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Objective: To create a function which takes a single String argument. The string is then evaluated and words in the String are reversed.
The output desired:
Ex: Hello World!
-- olleH !dlroW
*Question:* is how do I set up a loop so that I can separate the words from the sentence?
I am using a scanner to get the input from the user in the form of a String object.
Separating words is easy: see http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
String[] words = sentence.split(" ");
would result in words containing each word delimited by the spaces.
String source = "Hello World";
for (String part : source.split(" ")) {
System.out.print(new StringBuilder(part).reverse().toString());
System.out.print(" ");
}
Output:
olleH dlroW
Notes: Commenters have correctly pointed out a few things that I thought I should mention here. This example will append an extra space to the end of the result. It also assumes your words are separated by a single space each and your sentence contains no punctuation.
Credits: #William Brendel
String str = new Scanner(System.in).nextLine();
Stack<String> stack = new Stack<String>();
for (String s : str.split(" ")) {
stack.push(new StringBuilder(s).toString());
}
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
This specifically pushes it onto the stack and then pops it to reverse it.
I took some of your code E. Doroskevic, sorry!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have the string aaabbbccc.What is the best way to get bbb part?
UPD:
How to get ccc from aaabbbcccdddfff?
s.substring(s.indexOf("b"), s.lastIndexOf("b")-1)
StringUtils.substringBetween("aaabbbccc", "aaa", "ccc")
using StringUtils.substringBetween(...) from here
In this specific case,
String bbbString = "aaabbbccc".substring(3,6);
In response to the bit you just added to your question, I would say use the following function
public String getRepetitiveSubstringOf(String string, char desiredCharacter)
{
String theSubstring = null;
char[] charArray = string.toCharArray(); //it is more efficient to use arrays
//get the beginning position
int beginPosition = string.indexOf(desiredCharacter);
//get the end position (the desired substring length might NOT be 3, but rather, in this case,
//where the character value changes)
int endPosition = beginPosition;
//looping until we have either found a different character, or until we have hit the end of the
//character array (at the end, we loop one more time so that we can hit a garbage value that
//tells us to stop)
while ((charArray[endPosition] == desiredCharacter) || (endPosition < charArray.length))
{
endPosition++;
}
//if we have hit the garbage value
if (endPosition == charArray.length)
{
//we substring all the way to the end
theSubstring = string.substring(beginPosition);
}
else
{
//now, we check to see if our desiredCharacter was found AT ALL in the string
if (desiredCharacter > -1)
{
theSubstring = string.substring(beginPosition, endPosition);
}
}
return theSubstring;
}
From there, you can check for a return value of null
Try StringUtils.subStringBetween
String value = "aaabbbccc";
StringUtils.substringBetween(value, "aaa", "ccc");
For the string that you have specified you can use the code:
String result=s.substring(s.indexOf('b'),s.lastIndexOf('b'));
where s is your string,
For a more general string:
String result =s.substring(first index,last index);
where first index and last index are range that you want to extract.
Example:
String S="rosemary";
String result=s.substring(4,s.length());
This will store "mary" in the result string.
You only need one line and one method call if you use regex to capture the target group:
String middle = str.replaceAll(".*aaa(.*)ccc.*", "$1");
The best way maybe regEx.You could use
String str = str.replaceAll(a