There are functions available for multiple spaces to single space, but I want to add more spaces where single spaces are there.
I tried this:
int rem = b - temp.length();
for(int k = 0; k < rem; k++) {
temp.replace(" ", " ");
}
I want to add that much space between words as predefined length of string.
You only need to invoke temp.replace(" "," "); once (i.e. instead of looping) to replace all single spaces with two consecutive spaces.
However, since Strings are immutable, you need to assign temp with the outcome of your replace invocation.
temp = temp.replace(" "," ");
I will suggest you a combination of String.trim Method and REGEX
EXAMPLE:
public static void main(String[] args) {
String temp = "Is you see this is because ";
String replacedString = temp.trim().replaceAll(" +", " ");
System.out.println(temp);
System.out.println(replacedString);
}
this will correct the temp String to
Is you see this is because
Related
The code below works when number of strings in array is odd (3,5,7) however it does not work when the number is even. For example, if I use "my is the name" I get output
name is the name
public void randomTest() {
String str ="my is name";
//Step1: split so that I can get them in in array
String [] arrStr= str.split(" ");
for(int i=0;i<arrStr.length;i++){
//Step2: Using temp swap 1st and last
String temp = arrStr[0];
arrStr[0] = arrStr[arrStr.length-1];
arrStr[arrStr.length-1] = temp;
System.out.print(arrStr[i]+" ");
}
}
Any idea how can I make it work for even number of Strings? Thank You.
Since Arvind Kumar Avinash has shared the fixed solution, I just like to offer an alternative option: After splitting the string into String array, maybe you can simply swap the last and first values, and then join them together:
String str ="my is the name";
// split
String[] arrStr= str.split(" ");
// swap
String temp = arrStr[0];
arrStr[0] = arrStr[arrStr.length - 1];
arrStr[arrStr.length - 1] = temp;
// join them back
str = String.join(" ", arrStr);
System.out.println(str); // name is the my
You need to iterate the loop only for half of the length of the array i.e.
for (int i = 0; i < arrStr.length / 2; i++)
Also, you need to use the counter variable, i instead of the fixed values 0 and 1. Make sure to limit the indices in the range of 0 to length_of_array - 1 which is the range of indices of an array in Java.
Do it as follows:
public class Main {
public static void main(String[] args) {
String str = "my is the name";
String[] arrStr = str.split(" ");
// Swap the elements of the array
for (int i = 0; i < arrStr.length / 2; i++) {
String temp = arrStr[i];
arrStr[i] = arrStr[arrStr.length - i - 1];
arrStr[arrStr.length - i - 1] = temp;
}
// Display the array
for (int i = 0; i < arrStr.length; i++) {
System.out.print(arrStr[i] + " ");
}
}
}
Output:
name the is my
If you want to swap only the first word with the last word, you do not need a loop. You can simply so it as follows:
public class Main {
public static void main(String[] args) {
String str = "my is the name";
String[] arrStr = str.split(" ");
// Swap the first and the last words
String temp = arrStr[0];
arrStr[0] = arrStr[arrStr.length - 1];
arrStr[arrStr.length - 1] = temp;
// Display the array
for (int i = 0; i < arrStr.length; i++) {
System.out.print(arrStr[i] + " ");
}
}
}
Output:
name is the my
What you are currently doing is swapping the first and last elements n times, where n is the size of the array. This makes it so that when you have an even number of elements, for example, 2, then you are swapping the first and last elements, and then swapping them back to their original position, which is unswapped. This is also why it is working for an odd number of elements since you are swapping the first and last elements an even number of times and then once more. If you just want to swap the first and last elements, you can simply get rid of the for loop that you have and it will work properly.
public void randomTest() {
String str ="my is name";
//Step1: split so that I can get them in in array
String [] arrStr= str.split(" ");
//Step2: Using temp swap 1st and last
String temp = arrStr[0];
arrStr[0] = arrStr[arrStr.length-1];
arrStr[arrStr.length-1] = temp;
}
Afterwards, if you want to merge the strings back together, you can use
str = String.join(" ", arrStr);
or a StringBuilder object like so.
StringBuilder sb = new StringBuilder(arrStr[0]);
for (int i = 0; i < arrStr.length; i++) {
sb.append(" ").append(arrStr[i]);
}
str = sb.toString();
The effect of either of these will turn my name is foo into foo name is my, basically swapping the first and last words, and will work for a string with any length or number of words.
Easiest way is to substring first and last word from the sentence.
int first = name.indexOf(' '); // first "space" character that occurs
int last = name.lastIndexOf(' '); // last "space" character that occurs
String firstWord = name.substring(0, first); // substring first word from index 0 to index of first "space" character
String lastWord = name.substring(last, name.length()-1); // substring last word from index the of last "space" character to higher index o sentence
String midSentece = name.substring(first, last); // substring rest of the sentence
System.out.println(lastWord + midSentece + firstWord);
I have to write a program that takes a user's chemical equation as an input, like NaCl2, and separate it out into individual elements and the number associated with them. Is there a way to parse through a string and pair the individual elements, like in NaCl2 into Na and Cl2?
As you mentioned in a comment, checking whether letters are uppercase or lowercase is key to this problem. What you're looking for to solve this is the Character.isUppercase() method. Your code should iterate over the characters in the input String and pass each to this method. I wrote up this rough draft of a code to demonstrate it (and it also prints the output for you - how convenient!):
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> elements = new ArrayList<>();
System.out.print("Enter formula: ");
String formula = sc.next();
String s = "";
for (int i=0; i<formula.length(); i++) {
if (Character.isUpperCase(formula.charAt(i))) {
if (!s.isEmpty()) {
elements.add(s);
}
s = "" + formula.charAt(i);
} else {
s += formula.charAt(i);
}
}
elements.add(s);
for (int i=0; i<elements.size(); i++) {
System.out.print(elements.get(i) + " ");
}
System.out.println();
}
This can be done a number of ways. One of them is using regular expressions. In this case the expression looks for an uppercase character, followed optionally by a lower case character, followed optionally by a number.
Pattern elementPattern = Pattern.compile("(\\p{Upper}\\p{Lower}?)(\\p{Digit}*)");
This can be used to find all the elements in the input:
Matcher elementMatcher = elementPattern.match(input);
while (elementMatcher.find()) {
String element = elementMatcher.group(1);
String count = elementMatcher.group(2);
System.out.println("Element: " + element + " count: " + count);
}
The goal of this code was to create a program using main method java to analysis a piece text which has been entered from a user.
They do this by entering the text into a scanner which is then analysed by the program. The analysis is to produce word frequency, for example " This is a test" produces this results:
This is a test
1 letter words: 1
2 letter words: 1
3 letter words: 0
4 letter words: 2
5 letter words: 0
The bit that I'm stuck on is producing a mean/average, My guts telling to divide
counts.length by str.length but I'm not the Best at java and I've tried to implement this but all I get are errors. I'm not expecting anyone to just hand me code, but if someone could give me a hint in what I should do or just point me the right direction it would be greatly appreciated.
Code:
import java.util.Scanner;
public class Text_AD {
public static void main (String[] args) {
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
}}}
By average, I am assuming that you mean the mean length. I am also assuming you want to get a floating point mean. In which case you just need to divide the total of all the lengths in strings by the length of the array itself.
You could do something like the following;
int total = 0;
for(String s : strings) total += s.length();
System.out.println((double)total/strings.length);
I hope this helps.
Without breaking up your code much, you could run a for loop through your counts[] array, adding up all the values, and then dividing by counts.length to get the average.
Be aware of type casting though. You may want to do Double division instead of integer.
It this what you are looking for?
import java.util.Scanner;
public class While_Loop {
public static void main (String[] args) {
int lengthSum, wordCount;
lengthSum = wordCount = 0;
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
wordCount++;
lengthSum += str.length();
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
System.out.println("Average: " + lengthSum/wordCount);
}}}
NOTE: I only added stuff to your code. The way it is written is pretty messy. I'd clean up some of the for loops and the brackets at the end for practice making the code more readable.
When I understand you correct you should have one variable int totalCount = 0; where you add
totalCount += i*counts[i]; in your last for loop.
After the loop you can simply divide through the size-1 (because 0 does not count)
double average = totalCount/(counts.length-1);
Alternative way
You take the inputstring length without the spaces and divide it by the number of spaces + 1 (which is equal to the number of words)
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
System.out.println("Enter text: ");
String s = "This is a sample text";
System.out.println("" + s);
String[] strings = s.split(" ");
for(String str : strings) {
Integer counter = map.get(str.length())==null?0:map.get(str.length());
map.put(str.length(),counter++);
}
Integer sum=0;
Integer counter=0;
for(Integer len : map.keySet()) {
sum+=len*map.get(len);
counter+=map.get(len);
}
Double average = Double.valueOf(sum/counter);
Or you can combine the loops
Few suggestions which might help you (not related to the specific question).
Choose a meaningful class name rather than While_Loop .
Do, Scanner input = new Scanner(System.in); before the start of the loop.
As soon as you read each line, do the following.
Split the line using "\\s+" .
Create a HashMap with Key as Count (Integer) and Value as a list of Words with that count. Create this outside the loop.
For each split word,,get the length . and check if the map already contains the count, get the list (value), add he current word to it. else, add a new entry with the word as the single entry in the list.
Get the keySet of the map, add values of all keys i.e, *count * number of elements in the list*. then divide by total number of elements.
And yes, I know this is a very big change (something you might as well ignore..). But this is the right way to go.
This question already has answers here:
Reverse a given sentence in Java
(14 answers)
Closed 9 years ago.
I m inserting a string in my program
String str = " I live in India";
how can in get reversed string of that like
String str ="India in live I"
this is an interview question in my interview. Please any one can help me out in this question
Split it and then add it to a new String in reverse order.
String s = " I live in India";
String[] split = s.split(" ");
String result = "";
for (int i = split.length - 1; i >= 0; i--) {
result += (split[i] + " ");
}
System.out.println(result.trim());
This prints:
India in live I
Although short and straight-forward, this solution is not really effective in terms of time and memory. It somewhat depends on how the input is given (as a String or as something else) and whether we can modify the input in order to save computation resources.
Let's assume the sentence is given as an array of characters and we are allowed to modify it. We can then follow the following approach, which brings linear time (O(n)) and constant (O(1)) memory complexity:
What we will have as input would be:
char[] array = {'I',' ','l','i','v','e',' ','i','n',' ','I','n','d','i','a'};
Let's write a method that takes a char[] array and reverses the elements from start to end in-place:
void reverse(char[] array, int start, int end) {
while (start < end) {
char temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
First, we will reverse the whole array (in-place), using this method.
You can notice that after the reversal the words in the sentence are ordered in the desired (reversed) way. The problem is that each word is reversed:
{'a','i','d','n','I',' ','n','i',' ','e','v','i','l',' ','I'}
Let's now iterate the array from left to the right. We will reverse each word in-place, like we initially reversed the whole array. In order to do that, we need to keep an index (start), telling where does a word start and every time we encounter a space (' ') we will trigger a reverse between start and the character before the space. This way we will keep the desired order of words, but we will also have the characters in the words properly ordered.
The code should be self-explanatory:
void reverseSentence(char[] array) {
int n = array.length;
reverse(array, 0, n - 1);
int start = 0;
for (int i = 0; i < n; i++) {
if (array[i] == ' ') {
reverse(array, start, i - 1);
start = i + 1;
}
}
}
Calling this on the initial array, we get:
{'I','n','d','i','a',' ','i','n',' ','l','i','v','e', ' ','I'}
We can further construct a String out of it, or just print it. In any case, the sentence is reversed as desired.
This has linear complexity (O(n)), because each character is part of a reverse exactly once and is being tested for being a space exactly once.
As for memory-usage, we used only one additional variable (start), which makes the total memory complexity a constant (O(1)).
String str = "I live in India";
String result = "";
String[] words = str.split(" ");
for (int i=words.length-1;i>=0;i--){
result = result + words[i] + " ";
}
result = result.subString(result, 0, result.length-1); // remove the last " "
This code splits the String along the whitespaces, so that you get an array of the words.
Then a for loop iterates through the array from last to first element and appends the words plus a whitespace to the result string. Finally the whitepace after the last word is removed.
try this way
public class test {
public static void main(String args[])
{
String x="i live in india";
String y[]=x.split(" ");
System.out.println(y[3]+" "+y[2]+" "+y[1]+" "+y[0]);
// if the input string is different meaning if the number of words are greater than or less than four then try this way
/*for(int i=y.length-1;i>=0;i--)
{
System.out.print(y[i]+ " ");
}*/
}
}
this is the screenshot to show the output
I have a trouble with the for loop method that only loop 1 times whats is the problem? In the array was no problem at all, it able to print the value I want to.
here is my code:
public static void main(String[] args){
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++){
if(word[y].toString().equals("Apple2") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple3") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple4") ){
total++;
//str.append(word[y].toString());
}
else if(word[y].toString().equals("Apple1") ){
total++;
//str.append(word[y].toString());
}
}
System.out.println( word[0] + word[1] + word[2] + word[3] + word[4] + word.length);
System.out.println(str + "hihi" + total);
}
The others have nailed the cause of your problem. However, the fix they suggest is rather too specific ... and fragile. (Splitting with split("\\s*,\\s*") is better but it won't cope with whitespace at the start / end of the entire string.)
I suggest that you continue to use split(","), but trim the words before testing; e.g.
for (int y = 0; y < word.length; y++) {
String trimmed = word[y].trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
or better still:
String[] words = s.split(",");
for (String word : words) {
String trimmed = word.trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
That will make your code work irrespective of the whitespace characters around the commas and at the start and end of the string. Robustness is good, especially if it costs next to nothing to implement.
Finally, you could even replace the if / else if / ... stuff with a Java 7 String switch statement.
Try splitting on ", " (with space)
String[] word = s.split(", ");
without that space in split word[1] would look like " Apple1" instead "Apple1"
Other option would be calling word[y].trim().equals("Apple2") to get rid of that additional space, but I would say including it in split is better. If you aren't sure how many white-spaces can be near comma you can split this way split("\\s*,\\s*") to include all white-spaces around comma.
Also as Matt Ball pointed in his comment you don't need to call toString() on word[y] since it is already String.
you ignore the space during split. String[] word = s.split(", ");
You'are split by "," but your String contains ", ".
You can change the s.split(","); to s.split(", ");
Or trim the split's result like this :
public static void main(String[] args) {
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++) {
if (word[y].trim().equals("Apple2")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple3")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple4")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple1")) {
total++;
// str.append(word[y].toString());
}
}
System.out.println(word[0] + word[1] + word[2] + word[3] + word[4]
+ word.length);
System.out.println(str + "hihi" + total);
}
There is nothing wrong with your code but the problem lies in the String that you are giving to the variable.
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
Here the string contains spaces between them after the comma. So that when you split your string it splits like
word[0]= "Apple0"
word[1]= " Apple1"
word[2]= " Apple2"
word[3]= " Apple3"
and so on.
So that when you compare like
word[y].equals("Apple1") it returns false because " Apple1" and "Apple1" are two different strings. So that initialize your string like this
String s = "Apple0,Apple1,Apple2,Apple3,Apple4"; // without white spaces
It will work fine. Or you can use trim method in your existing code without changing String like
word[y].trim().equals("Apple1") //It will trim all the leading and trailing white spaces.
Hope this helps.