Skip to content

Instantly share code, notes, and snippets.

@HoussemNasri
Created April 9, 2021 17:11
Show Gist options
  • Save HoussemNasri/580d3369c6900d732a36396ac7b16d72 to your computer and use it in GitHub Desktop.
Save HoussemNasri/580d3369c6900d732a36396ac7b16d72 to your computer and use it in GitHub Desktop.
import java.util.List;
import java.util.ArrayList;
import java.util.*;
class Main {
public static void reversePhrase(String s) {
}
public static boolean isCharOrSpace(char c){
return isChar(c) || c == ' ';
}
public static boolean isChar(char c){
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z');
}
public static void main(String[] args) {
int index = 0;
String str = "hello world, welcome to my world";
List<String> phrases = new ArrayList<>();
while(index < str.length()){
if(str.charAt(index)==','){
index+=2;
}
String phrase = "";
while(index < str.length()
&& isCharOrSpace(str.charAt(index))){
phrase+=str.charAt(index);
index++;
}
if(phrase.length()>0){
phrases.add(phrase);
}
}
List<String> revPhrases = new ArrayList<>();
for(int i=0;i<phrases.size();i++){
String phrase = phrases.get(i);
String reversed = "";
boolean firstWord=true;
index = 0;
while(index < phrase.length()){
char c = phrase.charAt(index);
String word = "";
while(index < phrase.length()&&isChar(phrase.charAt(index)) ){
word+=phrase.charAt(index);
index++;
}
if(word.length()>0){
String spacedWord = word;
if(firstWord){
firstWord=false;
}else{
spacedWord+=" ";
}
reversed = spacedWord+reversed;
}
//skip space between words
index++;
}
if(reversed.length()>0){
revPhrases.add(reversed);
}
}
for(int i =0;i<revPhrases.size();i++)
{
System.out.println(revPhrases.get(i));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment