I'd like to reverse a string word by word except the last letter of each word.
For example: "Hello how are you" -> lleHo ohw rae oyu
but I am getting output as: olleH woh era uoy
I'm not able to fix the last letter of each word.
This is my Java code for the above output:
public class Main
{
public static void main(String[] args) {
String s = "Hello how are you ";
char [] ch = s.toCharArray();
System.out.println(ch.length);
int pos=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==' ')
{
for(int j=i;j>=pos;j--)
{
System.out.print(ch[j]);
}
pos=i+1;
}
}
}
}
Below is the solution to solve the problem:
public class Main {
public static void main(String[] args) {
//call the reverseSentence Method
reverseSentence("Hello how are you");
}
public static void reverseSentence(String sentence) {
//Replacing multiple space with a single space
sentence = sentence.replaceAll("[ ]{2,}", " ");
//Split the array and store in an array
String [] arr = sentence.split(" ");
StringBuilder finalString = new StringBuilder();
//Iterate through the array using forEach loop
for(String str : arr) {
//Creating substring of the word, leaving the last letter
String s = str.substring(0, str.length() - 1);
//Creating StringBuilder object and reversing the String
StringBuilder sb = new StringBuilder(s);
//Reversing the string and adding the last letter of the work again.
s = sb.reverse().toString() + str.charAt(str.length() - 1);
//Merging it with the final result
finalString.append(s).append(" ");
}
//Printing the final result
System.out.println(finalString.toString().trim());
}
}
What I have done is, firstly split all the words on spaces and store it inside an array. Now iterate through the array and get the substring from each word leaving the last letter of each word. And then I am using StringBuilder to reverse the String. Once that is done I am adding the last letter of the word to the reversed string and merging it with the finalString which is created.
I'd use regex replaceAll with a lambda to handle the reversal. \S+ matches any sequence of non-space characters. This has the advantage of elegantly handling arbitrary whitespace. You could use \w+ if you want to avoid reversing punctuation characters, although matching words like "isn't" and so forth suggests the problem devolves into natural language processing. I assume your specification is not so complex, though.
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
String res = Pattern
.compile("\\S+")
.matcher("Hello how are you")
.replaceAll(m -> {
String s = m.group();
return new StringBuilder(s.substring(0, s.length() - 1))
.reverse().toString() + s.charAt(s.length() - 1);
});
System.out.println(res); // => lleHo ohw rae oyu
}
}
How do you think of this solution?
public class Main
{
public static void main(String[] args) {
String s = "Hello how are you ";
char [] ch = s.toCharArray();
System.out.println(ch.length);
int pos=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==' ')
{
System.out.print(ch[i]);
for(int j=i-2;j>=pos;j--)
{
System.out.print(ch[j]);
}
System.out.print(ch[i-1]);
pos=i+1;
}
}
}
}
public class Main {
public static void main(String[] args) {
String s = "Hello how are you ";
final List<String> list = Arrays.asList(s.split(" "));
StringBuilder builder = new StringBuilder();
list.forEach(item ->{
StringBuilder itemBuilder = new StringBuilder(item);
final String rStr = itemBuilder.reverse().toString();
builder.append(rStr.substring(1,rStr.length())).append(rStr.substring(0,1)).append(" ");
});
System.out.println(builder.toString());
}
}
FP style:
String str = "Hello how are you";
String res = Arrays.stream(str.split(" "))
.map(s ->
new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString() + s.substring(s.length() - 1)
)
.reduce((s, s1) -> s + " " + s1)
.orElse("");
System.out.println(res); // lleHo ohw rae oyu
A simpler solution would be to just use the Java Stack data structure for each word (after a string.split) and just add each letter (except token.length-1).
public static void main(String[] args) {
String string = "Hello how are you ";
final String[] tokens = string.split(" ");
for (String token : tokens) {
final Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < token.length()-1; i++) {
stack.push(token.charAt(i));
}
while (!stack.empty()) {
System.out.print(stack.pop());
}
System.out.print(token.charAt(token.length()-1) + " ");
}
}
I am trying to use a method to reverse the characters in a string and I keep getting a type mismatch error. Any thoughts?
public static String userReverse (String userEntry3) {
String reverse = "";
for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
reverse = System.out.println(userEntry3.charAt(i));
}
return reverse;
}
System.out.println is a void method. It returns nothing. So it cannot assigned back to a String variable
Your code is wrong.
If you want to reverse a string, you can use this:
public static String userReverse (String userEntry3) {
return new StringBuilder(userEntry3).reverse().toString()
}
Get rid of System.out.println and add a += to concatenate the new char
public static String userReverse (String userEntry3) {
String reverse = "";
for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
reverse += userEntry3.charAt(i);
}
return reverse;
}
EDIT: As Tim said in the comments, StringBuilder can be used too (and is better practice than concatenating strings in a loop):
public static String userReverse (String userEntry3) {
StringBuilder reverse = new StringBuilder();
for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
reverse.append(userEntry3.charAt(i));
}
return reverse.toString();
}
A more optimized way to reverse a string includes two pointer approach:
Use one pointer to start from the beginning and the other to start from the end. By the time they meet each other your string is already reversed
public static String userReverse (String userEntry3) {
int i = 0;
int j = userEntry3.length()-1;
StringBuilder myName = new StringBuilder(userEntry3);
for(; i < j ; i++,j--){
char temp = userEntry3.charAt(i);
myName.setCharAt(i,userEntry3.charAt(j));
myName.setCharAt(j,temp);
}
return myName.toString();
}
System.out.println() is a void method and it not return anything. you should try it this way,
public static String userReverse (String userEntry3) {
String reverse = "";
for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
reverse += userEntry3.charAt(i).toString();
}
return reverse;
}
I'm going bonkers on my java assignment. I'm rather new to methods and I can't seem to get my head around this one. Could you perhaps give me a guiding hand?
I'm trying to convert an array of int to a string and print it using the. toString method. We are not allowed to use some libraries though. All I get from my code is a 'stack overflow'...
Code:
public static void main(String[] args) {
int[] arr = {3,4,5,6,7};
String str = toString(arr);
System.out.println("arr = " + str);
}
private static String toString(int[] arr) {
String str = Arrays.toString(arr);
return str;
}
This is the complete code of my program so far:
public class Arrays {
public static void main(String[] args) {
int[] arr = {3,4,5,6,7};
int result = sum(arr);
System.out.println(result);
String str = toString(arr);
System.out.println("arr = " + str);
}
private static int sum(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i];
}
return result;
}
private static String toString(int[] arr) {
String str = Arrays.toString(arr);
return str;
}
}
The result in my console:
25
Exception in thread "main" java.lang.StackOverflowError
at tb222kc_lab3.Arrays.toString(Arrays.java:24)
at tb222kc_lab3.Arrays.toString(Arrays.java:24)
at tb222kc_lab3.Arrays.toString(Arrays.java:24).....
Change your Arrays.toString(arr) in toString Method to java.util.Arrays.toString(arr)
Your code has gone into recursive call because you have named your class as Arrays
Then I will create my own toString like this :
public String toString(int[] arr) {
StringBuilder result = new StringBuilder();
result.append("[");
for (int a : arr) {
result.append(a);
}
result.append("]");
return result.toString();
}
Your toString() method should look like this:
private static String toString(int[] arr) {
String str = "[";
for (int index = 0; index < arr.length; index++) {
// Concat the string with the int value.
str += arr[index];
// Add delimiter only if we're not at the last index.
if (index < arr.length - 1) {
str += ", ";
}
}
str += "]";
return str;
}
I will only add to this that college professors are notorious for giving their students requirements that have no bearing on real life (like don't use libraries).
I need to reverse 5 or more character long words in a given string. For example:
* Given string: My name is Michael.
* Output: My name is leahciM.
Rest of the sentence stays the same, just those long words get reversed.
So far I came up with this:
public static String spinWords(String sentence) {
String[] splitWords = sentence.split(" ");
String reversedSentence = "";
String reversedWord = "";
for (String str : splitWords) {
if (str.length() >= 5) {
for (int i = str.length() - 1; i >= 0; i--)
reversedWord += (str.charAt(i) + " ");
}
}
}
And I have reversed those words, but
1) they are in one string, without a space
2) I dont know how to put them back into their places in string
Here is a suggestion:
write a method that reverses a string:
private static String reverse(String s) { ... }
then in your main method, call it when necessary:
if (str.length() >= 5) str = reverse(str);
you then need to put the words back together, presumably into the reversedSentence string:
reversedSentence += str + " "; //you will have an extra space at the end
Side notes:
using a StringBuilder may prove more efficient than string concatenation for longer sentences.
you could put all the words back into a List<String> within the loop and call reversedSentence = String.join(" ", list) after the loop
reversing a string can be done in one line - you should find numerous related Q&As on stackoverflow.
You can use StringBuilder
public static String spinWords(String sentence) {
String[] splitWords = sentence.split(" ");
StringBuilder builder = new StringBuilder();
for (String str : splitWords) {
if (str.length() < 5) {
builder.append(str);
else
builder.append(new StringBuilder(str).reverse().toString());
builder.append(" ");
}
return builder.toString().trim();
}
No need to use anything else you almost had it, just check your "for" loops and remember to add the unreversed string.
public static String spinWords(String sentence) {
String[] splitWords = sentence.split(" ");
String reversedSentence = "";
String reversedWord;
for (String str : splitWords) {
if (str.length() >= 5) {
reversedWord = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversedWord += (str.charAt(i));
}
reversedSentence += " " + reversedWord;
} else {
reversedSentence += " " + str;
}
}
return reversedSentence;
}
Use StringBuilder to build the answer as you process the elements in splitWords.
You may also find the idiom of space with special first-time value (being "") useful.
There was also a bug in your original code.
So here is what I would do:
public class ReverseLongWord {
public static void main(String[] args) {
String testInput = "My name is Michael";
System.out.println(spinWords(testInput));
}
public static String spinWords(String sentence) {
String[] splitWords = sentence.split(" ");
String reversedSentence = "";
StringBuilder sb = new StringBuilder();
String space = ""; // first time special
String reversedWord = "";
for (String str : splitWords) {
if (str.length() >= 5) {
for (int i = str.length() - 1; i >= 0; i--) {
reversedWord += (str.charAt(i)); // Bug fixed
}
sb.append(space + reversedWord);
} else {
sb.append(space + str);
}
space = " "; // second time and onwards
}
return sb.toString();
}
}
The output of this program is the following, as you have specified:
My name is leahciM
I think the reverse method as some people suggest would be the easiest way, here I share my implementation
public static void main(String[] args) {
System.out.println(concatenatePhrase("My name is Michael"));
System.out.println(concatenatePhrase("Some randoms words with differents sizes and random words"));
}
private static String concatenatePhrase(String phrase) {
StringBuilder completePhrase = new StringBuilder();
String[] phrases = phrase.split(" ");
for (String word : phrases) {
if (word.length() >= 5) {
completePhrase.append(reverseWord(word).append(" "));
} else {
completePhrase.append(word).append(" ");
}
}
return completePhrase.toString().trim();
}
private static StringBuilder reverseWord(String wordPassed) {
StringBuilder word = new StringBuilder(wordPassed);
return word.reverse();
}
I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.
You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.
I'm going to assume that this is homework, so I will only give snippets as hints:
Finding indices of all occurrences of a given substring
Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:
String text = "012ab567ab0123ab";
// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
String API links
int indexOf(String, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.
Related questions
Searching for one string in another string
Extracting substrings at given indices out of a string
This snippet extracts substring at given indices out of a string and puts them into a List<String>:
String text = "0123456789abcdefghij";
List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));
System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"
String[] partsArray = parts.toArray(new String[0]);
Some key ideas:
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Works especially nicely if you don't know how many parts there'll be in advance
String API links
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Related questions
Fill array with List data
You do now that most of the java standard libraries are open source
In this case you can start here
Use String tokenizer to split strings in Java without split:
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
This is the right answer
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
/**
* My method split without javas split.
* Return array with words after mySplit from two texts;
* Uses trim.
*/
public class NoJavaSplit {
public static void main(String[] args) {
String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}
private static String [] mySplit(String text1, String text2) {
text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
you can try, the way i did `{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(int i = 0; i <str.length();i++) {
if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string
System.out.println();
continue;
}
System.out.print(str.charAt(i));
}
sc.close();
}`
The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?
The way to go is to define the function you need first. In this case, it would probably be:
String[] split(String s, String separator)
The return type doesn't have to be an array. It can also be a list:
List<String> split(String s, String separator)
The code would then be roughly as follows:
start at the beginning
find the next occurence of the delimiter
the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
continue with step 2 until you have reached the end of the string
There are many fine points that you need to consider:
What happens if the string starts or ends with the delimiter?
What if multiple delimiters appear next to each other?
What should be the result of splitting the empty string? (1 empty field or 0 fields)
You can do it using Java standard libraries.
Say the delimiter is : and
String s = "Harry:Potter"
int a = s.find(delimiter);
and then add
s.substring(start, a)
to a new String array.
Keep doing this till your start < string length
Should be enough I guess.
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class WithoutSpit_method {
public static void main(String arg[])
{
char[]str;
String s="Computer_software_developer_gautam";
String s1[];
for(int i=0;i<s.length()-1;)
{
int lengh=s.indexOf("_",i);
if(lengh==-1)
{
lengh=s.length();
}
System.out.print(" "+s.substring(i,lengh));
i=lengh+1;
}
}
}
Result: Computer software developer gautam
Here is my way of doing with Scanner;
import java.util.Scanner;
public class spilt {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String to be Spilted : ");
String st = input.nextLine();
Scanner str = new Scanner(st);
while (str.hasNext())
{
System.out.println(str.next());
}
}
}
Hope it Helps!!!!!
public class StringWitoutPre {
public static void main(String[] args) {
String str = "md taufique reja";
int len = str.length();
char ch[] = str.toCharArray();
String tmp = " ";
boolean flag = false;
for (int i = 0; i < str.length(); i++) {
if (ch[i] != ' ') {
tmp = tmp + ch[i];
flag = false;
} else {
flag = true;
}
if (flag || i == len - 1) {
System.out.println(tmp);
tmp = " ";
}
}
}
}
In Java8 we can use Pattern and get the things done in more easy way. Here is the code.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
static void splitString(String s, int index) {
char[] firstPart = new char[index];
char[] secondPart = new char[s.length() - index];
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (i < index) {
firstPart[i] = s.charAt(i);
} else {
secondPart[j] = s.charAt(i);
if (j < s.length()-index) {
j++;
}
}
}
System.out.println(firstPart);
System.out.println(secondPart);
}
import java.util.Scanner;
public class Split {
static Scanner in = new Scanner(System.in);
static void printArray(String[] array){
for (int i = 0; i < array.length; i++) {
if(i!=array.length-1)
System.out.print(array[i]+",");
else
System.out.println(array[i]);
}
}
static String delimeterTrim(String str){
char ch = str.charAt(str.length()-1);
if(ch=='.'||ch=='!'||ch==';'){
str = str.substring(0,str.length()-1);
}
return str;
}
private static String [] mySplit(String text, char reg, boolean delimiterTrim) {
if(delimiterTrim){
text = delimeterTrim(text);
}
text = text.trim() + " ";
int massValue = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reg) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text.length(); j++) {
if (text.charAt(j) == reg) {
splitArray[i] = text.substring(0, j);
text = text.substring(j + 1, text.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the sentence :");
String text = in.nextLine();
//System.out.println("Enter the regex character :");
//char regex = in.next().charAt(0);
System.out.println("Do you want to trim the delimeter ?");
String delch = in.next();
boolean ch = false;
if(delch.equalsIgnoreCase("yes")){
ch = true;
}
System.out.println("Output String array is : ");
printArray(mySplit(text,' ',ch));
}
}
Split a string without using split()
static String[] splitAString(String abc, char splitWith){
char[] ch=abc.toCharArray();
String temp="";
int j=0,length=0,size=0;
for(int i=0;i<abc.length();i++){
if(splitWith==abc.charAt(i)){
size++;
}
}
String[] arr=new String[size+1];
for(int i=0;i<ch.length;i++){
if(length>j){
j++;
temp="";
}
if(splitWith==ch[i]){
length++;
}else{
temp +=Character.toString(ch[i]);
}
arr[j]=temp;
}
return arr;
}
public static void main(String[] args) {
String[] arr=splitAString("abc-efg-ijk", '-');
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.