I want to separate words and print them in a single line with a hyphen(-) in between. I have written the following code but it only prints the last word followed by a hyphen i.e. the output is carrot-. I don't understand why and what changes do I make to get the desired output?
public class SeparatingWords {
public static void main(String[] args) {
String str = "apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str) {
String[] words = str.split(" ");
String result = null;
for (int i = 0; i < words.length; i++) {
result=words[i]+"-";
}
return result;
}
}
Instead of calling a split and concatenating the string, why can't you directly call replaceAll directly to achieve your goal. This will make your code simple.
String result = str.replaceAll(" ", "-");
Below is sample modified code of yours. Hope this helps
public class Sample {
public static void main(String[] args) {
String str = "apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str) {
String result = str.replaceAll(" ", "-");
return result;
}
}
If you want to perform any other operation based on your requirement inside the method, then below should work for you. As suggested by #Moler added += and initialized the result object
public static String separatingWords(String str) {
String[] words = str.split(" ");
String result = ""; // Defaulted the result
for (int i = 0; i < words.length-1; i++) {
result += words[i] + "-"; // Added a +=
}
result += words[words.length - 1];
return result;
}
public class SeparatingWords
{
public static void main(String[] args)
{
String str="apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str)
{
String[] words=str.split(" ");
String result="";
for(int i=0;i<words.length;i++)
{
result += words[i]+"-";
}
return result;
}
}
Try this code:
public class SeparatingWords
{
public static void main(String[] args)
{
String str="apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str)
{
String[] words=str.split(" ");
String result=words[0];
for(int i=1;i<words.length;i++)
{
result=result+"-"+words[i];
}
return result;
}
}
You could use s StringBuilder, append the single word and a hyphon and at the last word, you just append the word:
public class SeparatingWords {
public static void main(String[] args) {
String str = "apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str) {
String[] words = str.split(" ");
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
resultBuilder.append(words[i]);
if (i != words.length - 1) {
resultBuilder.append("-");
}
}
return resultBuilder.toString();
}
}
String[] words = str.split(" ");
// perform operations on individual words
return String.join("-", words);
Related
This is my code
public class StringTest {
public static void main(String []args) {
String str= "8650";
StringBuilder build = new StringBuilder(str);
char index = str.charAt(0);
System.out.println(index+"");
int indexStr= build.indexOf(index+"");
System.out.println(indexStr);
for( int i = 0; i < str.length(); i++) {
if(indexStr == 0)
build.deleteCharAt(indexStr);
}
System.out.println(build);
}
}
I want to delete thé first number if it’s 0
So if I have 8650 it will print 8650, instead if I have 0650 it will print 650.
You have made things complicated,just use String.startsWith() and String.substring()`` can do it
public class StringTest {
public static void main(String[] args) {
String str = "8650";
str = "0650";
if (str.startsWith("0")) {
str = str.substring(1);
}
System.out.println(str);
}
}
Below code might help you.
public static void main(String[] args) {
String val = "10456";
val = (val.charAt(0) == '0') ? val.substring(1, val.length()) : val;
System.out.println(val);
}
It will remove all leading zero.
public static void main(String[] args) {
String str = "000650";
str = str.replaceFirst("^0*", "");
System.out.println(str); // output 650 it will remove all leading zero
}
suppose we have
String str = "Hello-Hello1";
How do we split it and compare it to see if it is equal or not?
This is what I wrote, but it does not give me the result.
public static void main(String[] args) {
String str = "Hello-Hello1";
String [] a = str.split("-");
for(int i=0; i<a.length; i++) {
System.out.print(a[i]+ " ");
}
for(int first =0; first<a.length; first++) {
for(int second =first+1; second<a.length; second ++) {
if(a[first].equals(a[second])){
System.out.println(a[first]);
}
}
}
}
First, you split your string like shown here:
How to split a string in Java, then compare them using the equals method: a[0].equals(a[1]);
Thank you all for helping
Here is the answer
public class SplitStringAndCompare {
public static void main(String[] args) {
String str = "Hello-Hello1";
String [] a = str.split("-");
if(a[0].equals(a[1])) {
System.out.println(a[0]+ " is equal to " + a[1]);
} else {
System.out.println(a[0]+ " is not equal to "+ a[1]);
}
}
public class SplitTest {
public static void main(String[] args) {
String string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String[] strToSplit = new String[] { "GH", "MN" };
for (String de : strToSplit) {
if (string.contains(de)) {
String[]str = string.split(de);
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
}
}
Output :
ABCDEF,IJKLMNOPQRSTUVWXYZ,ABCDEFGHIJKL,OPQRSTUVWXYZ
but actual output is :
ABCDEF,IJKL,OPQRSTUVWXYZ
You can do it another way like replace string by unique delimiter at first place instead of splitting string at first place .Later you can split whole string by unique delimiter. for ex.
public class SplitTest {
public static void main(String[] args) {
String string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String str;
String[] strToSplit = new String[] { "GH", "MN" };
for (String de : strToSplit) {
if (string.contains(de)) {
str = string.replace(de,unique_delimiter);
}
}
String [] finalString = str.split(unique_delimiter);
for (int i = 0; i < finalString.length; i++) {
System.out.println(finalString[i]);
}
}
}
Hope this would help.
Is there something I am doing wrong here? When printed I get "*" and I need to get "-32". I am parsing each individual word and returning the last word.
public static void main(String[] args) {
System.out.println(stringParse("3 - 5 * 2 / -32"));
}
public static String stringParse(String string) {
String[] word = new String[countWords(string)];
string = string + " ";
for (int i = 0; i <= countWords(string); i++) {
int space = string.indexOf(" ");
word[i] = string.substring(0, space);
string = string.substring(space+1);
}
return word[countWords(string)];
}
public static int countWords(String string) {
int wordCount = 0;
if (string.length() != 0) {
wordCount = 1;
}
for (int i = 0; i <= string.length()-1; i++){
if (string.substring(i,i+1).equals(" ")) {
wordCount++;
}
}
return wordCount;
}
You could instead split the string by white space using "\\s+" and return the last element of that array. This will return the last word.
public static String stringParse(String s){
return s.split("\\s+")[s.split("\\s+").length-1];
}
In this case you can use regular expressions too :
public static void main(String[] args) {
System.out.println(stringParse("3 - 5 * 2 / -32"));
}
public static String stringParse(String string) {
String found = null;
Matcher m = Pattern.compile("\\s((\\W?)\\w+)$", Pattern.CASE_INSENSITIVE)
.matcher(string);
while (m.find()) {found = m.group();}
return found;
}
Im trying to make a program to take input for a string from the scanner, but i want to break up the string that was inputed and reverse the order of words. This is what i have so far.
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
StringBuilder welcome = new StringBuilder(input.next());
int i;
for( i = 0; i < welcome.length(); i++ ){
// Will recognize a space in words
if(Character.isWhitespace(welcome.charAt(i))) {
Character a = welcome.charAt(i);
}
}
What I want to do is after it recognizes the space, capture everything before it and so on for every space, then rearrange the string.
Edit after questions.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main( String[] args ) {
final String welcome = "How should we get words in string form a List?";
final List< String > words = Arrays.asList( welcome.split( "\\s" ));
Collections.reverse( words );
final String rev = words.stream().collect( Collectors.joining( ", " ));
System.out.println( "Your sentence, reversed: " + rev );
}
}
Execution:
Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How
I did suggest first reverse the whole string.
Then reverse the substring between two spaces.
public class ReverseByWord {
public static String reversePart (String in){
// Reverses the complete string
String reversed = "";
for (int i=0; i<in.length(); i++){
reversed=in.charAt(i)+reversed;
}
return reversed;
}
public static String reverseByWord (String in){
// First reverses the complete string
// "I am going there" becomes "ereht gniog ma I"
// After that we just need to reverse each word.
String reversed = reversePart(in);
String word_reversal="";
int last_space=-1;
int j=0;
while (j<in.length()){
if (reversed.charAt(j)==' '){
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
word_reversal=word_reversal+" ";
last_space=j;
}
j++;
}
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
return word_reversal;
}
public static void main(String[] args) {
// TODO code application logic here
System.out.println(reverseByWord("I am going there"));
}
}
Here is the way you can reversed the word in entered string:
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();
if(!s.trim().contains(' ')) {
return s;
}
else {
StringBuilder reversedString = new StringBuilder();
String[] sa = s.trim().split(' ');
for(int i = sa.length() - 1; i >= 0: i - 1 ) {
reversedString.append(sa[i]);
reversedString.append(' ');
}
return reversedString.toString().trim();
}
Hope this helps.
If you wanted to reduce the number of line of code, I think you can look into my code :
package com.sujit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StatementReverse {
public static void main(String[] args) throws IOException {
String str;
String arr[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string:");
str = br.readLine();
arr = str.split("\\s+");
for (int i = arr.length - 1;; i--) {
if (i >= 0) {
System.out.print(arr[i] + " ");
} else {
break;
}
}
}
}
public class StringReverse {
public static void main(String[] args) {
String str="This is anil thakur";
String[] arr=str.split(" ");
StringBuilder builder=new StringBuilder("");
for(int i=arr.length-1; i>=0;i--){
builder.append(arr[i]+" ");
}
System.out.println(builder.toString());
}
}
Output: thakur anil is This
public class ReverseWordTest {
public static String charRev(String str) {
String revString = "";
String[] wordSplit = str.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
String revWord = "";
String s2 = wordSplit[i];
for (int j = s2.length() - 1; j >= 0; j--) {
revWord = revWord + s2.charAt(j);
}
revString = revString + revWord + " ";
}
return revString;
}
public static void main(String[] args) {
System.out.println("Enter Your String: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(charRev(str));
}
public static void main(String[]args)
{
String one="Hello my friend, another way here";
String[]x=one.split(" ");
one="";
int count=0;
for(String s:x){
if(count==0||count==x.length) //that's for two edges.
one=s+one;
else
one=s+" "+one;
count++;
}
System.out.println(one); //reverse.
}