move first word to the end of the sentence? - java

Here is SS of the whole question. http://prntscr.com/1dkn2e
it should work with any sentence not just the one given in the example
I know it has to do something with strings. Our professor has gone over with these string methods
http://prntscr.com/1dknco
This is only a basic java class so don't use any complicated stuff
here is what I have, don't know what to do after this
any help would be appreciated.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
}
}

You can use public String[] split(String regex):
splitted = sentence.split("\\s+");
splitted[0] Is the first word.
splitted[splitted.length - 1] Is the last word.
Since your'e not allowed to use String#split, you can do this trick:
myString = myString.substring(0, myString.lastIndexOf(" ")) + firstWord;
By doing this, you'll have a substring which contains the sentence without the last word. (For extracting the first word, you can use String#indexOf.
firstWord is the first word you extracted before (I'll not solve the whole problem for you, try to do it by yourself, it should be easy now)

Well as it seem your looking for very simple string arithmetic.
So that's the simplest i could do:
// get the index of the start of the second word
int index = line.indexOf (' ');
// get the first char of the second word
char c = line.charAt(index+1);
/* this is a bit ugly, yet necessary in order to convert the
* first char to upper case */
String start = String.valueOf(c).toUpperCase();
// adding the rest of the sentence
start += line.substring (index+2);
// adding space to this string because we cut it
start += " ";
// getting the first word of the setence
String end = line.substring (0 , index);
// print the string
System.out.println(start + end);

try this
String str = "Java is the language";
String first = str.split(" ")[0];
str = str.replace(first, "").trim();
str = str + " " + first;
System.out.println(str);

Here is Another way you can do this.
UPDATED: Without Loops
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
int spacePosition = sentence.indexOf(" ");
String firstString = sentence.substring(0, spacePosition).trim();
String restOfSentence = sentence.substring(spacePosition, sentence.length()).trim();
String firstChar = restOfSentence.substring(0, 1);
firstChar = firstChar.toUpperCase();
restOfSentence = firstChar + restOfSentence.substring(1, restOfSentence.length());
System.out.println(restOfSentence + " " + firstString);
keyboard.close();

Related

How to get rid of white space in palindrome (Java)

public class reverserapp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter a word");
String str = scan.nextLine();
String reverse = "";
for( int i = str.length() - 1; i >= 0; i--)
reverse += str.charAt(i);
if(reverse.equalsIgnoreCase(str))
System.out.println("Palindrome");
else System.out.println("Not Palindrome");
}
}
This is my palindrome code. I'm doing this for a small assignment. I can get single words to work but if I write a something like "Don’t nod" it shows up as not palindrome. How can I achieve this? I'd like for my code to ignore punctuation's and white space.
So in the end result should be like "dontnod"
Thanks in advance for any help, complete noob at this.
Remove all non-letter characters, then put the resulting String to lower case .
str = str.replaceAll("[^a-zA-Z]", "");
str = str.toLowerCase();
You can use the replace function from StringUtils.
Example:
StringUtils.replace("asdasd aaaa", " ", ""); //-> output: asdasdaaaa
You can define a regex to remove punctuation and space, and perform a String replace on input, e.g.:
String regex = "[\\p{Punct}\\s]";
String input = "don't nod";
System.out.println(input.replaceAll(regex, ""));

String Array for Java

I have a question regarding making String arrays in Java. I want to create a String array that will store a specific word in each compartment of the string array. For example, if my program scanned What is your deal? I want the word What and your to be in the array so I can display it later.
How can I code this? Also, how do I display it with System.out.println();?
Okey so, here is my code so far:
import java.util.Scanner;
import java.util.StringTokenizer;
public class OddSentence {
public static void main(String[] args) {
String sentence, word, oddWord;
StringTokenizer st;
Scanner scan = new Scanner (System.in);
System.out.println("Enter sentence: ");
sentence = scan.nextLine();
sentence = sentence.substring(0, sentence.length()-1);
st = new StringTokenizer(sentence);
word = st.nextToken();
while(st.hasMoreTokens()) {
word = st.nextToken();
if(word.length() % 2 != 0)
}
System.out.println();
}
}
I wanted my program to count each word in a sentence. If the word has odd numbers of letter, it will be displayed.
Based on what you've given alone, I would say use #split()
String example = "What is your deal?"
String[] spl = example.split(" ");
/*
args[0] = What
args[1] = is
args[2] = your
args[3] = deal?
*/
To display the array as a whole, use Arrays.toString(Array);
System.out.println(Arrays.toString(spl));
To read and split use String.split()
final String input = "What is your deal?";
final String[] words = input.split(" ");
To print them to e.g. command line, use a loop:
for (String s : words) {
System.out.println(s);
}
or when working with Java 8 use a Stream:
Stream.of(words).forEach(System.out::println);
I agree with what the others have said, you should use String.split(), which separates all elements on the provided character and stores each element in the array.
String str = "This is a string";
String[] strArray = str.split(" "); //splits at all instances of the space & stores in array
for (int i = 0; i < strArray.length(); i++) {
if((strArray[i].length() % 2) == 0) { //if there is an even number of characters in the string
System.out.println(strArray[i]); //print the string
}
}
Output:
This is string
If you want to print the string when it has an odd number of characters, simply change if((strArray[i].length() % 2) == 0) to if((strArray[i].length() % 2) != 0)
This will give you just a as the output (the only word in the string with an odd number of characters).
Let input be your input string. Then:
String[] words = input.split(" ");

How to change the first word of a string into uppercase using only String class

I am working on a Java Lab and have completed about 5 of 7 tasks of manipulating a string entered by the end-user. One task however is to change the first word only of the string to all upper case. We are only allowed to use methods of the String class (StringBuffer & StringBuilder not allowed), which makes this a bit more manual.
Converting an entire string to uppercase is easy enough:
String upper = userInput.toUpperCase();
But only part of the string is tricking me.
I'm thinking of doing a while loop where each string index gets converted into uppercase until the loop reaches a ' '. So something like this:
String stringCapped = "";
String stringRemaining = "";
//get the string from the end-user
Scanner scan = new Scanner(System.in);
System.out.println("Please enter any string: ");
String userInput = scan.nextLine();
//find the length of the string
int stringLength = userInput.length();
while (userInput.charAt(charSearch) != ' '){
//Here I need to replace each char with an uppercase until I reach a space
//then add the remaining string.
stringCapped = userInput.toUpperCase(charAt(charSearch))... + stringRemaining;
charSearch = ++charSearch;
}
Basically "Hello World" needs to become "HELLO World"
Please help, thanks!
You can try some thing like this
// get the string from the end-user
Scanner scan = new Scanner(System.in);
System.out.println("Please enter any string: ");
String userInput = scan.nextLine();
// find the length of the string
int stringLength = userInput.length();
int firstWordEnd = userInput.indexOf(" ");
String firstWord = userInput.substring(0, firstWordEnd);
String newFirstWord = firstWord.toUpperCase();
System.out.println(userInput.replace(firstWord, newFirstWord));
try:
String orginal = "asdasd asda sdasdojk kjsdhfk hsdjfhdjs fhdsjf jhdf ";
System.out.println(orginal);
String firstWord = orginal.substring(0, orginal.indexOf(' '));
System.out.println(orginal.replace(firstWord, firstWord.toUpperCase()));
result:
asdasd asda sdasdojk kjsdhfk hsdjfhdjs fhdsjf jhdf
ASDASD asda sdasdojk kjsdhfk hsdjfhdjs fhdsjf jhdf
Try:
int spaceIndex = userInput.indexOf(' ');
String upper = userInput.split(0, spaceIndex).toUpperCase() + userInput.split(spaceIndex);
Let s be your string then string(s.charAt(0)).toUppercase().concat(s.substring(1)) should do. Not tried myself. You can look here (http://docs.oracle.com/javase/6/docs/api/java/lang/String.html) if it doesn't work.
And the winner is:
String userInput = "abc def abc nbc wral abc def nbc abc";
String[] words = userInput.split(" ", 2); // split in 2 parts
System.out.println(words[0].toUpperCase() + " " + words[1]);
Here is the output:
ABC def abc nbc wral abc def nbc abc

Replacing a letter in a string with a char

String lower = Name.toLowerCase();
int a = Name.indexOf(" ",0);
String first = lower.substring(0, a);
String last = lower.substring(a+1);
char f = first.charAt(0);
char l = last.charAt(0);
f = Character.toUpperCase(f);
l = Character.toUpperCase(l);
String newname = last +" "+ first;
System.out.println(newname);
i want to take variables F and L and replace the lowercase first letters in last and first so they will be uppercase. How can I do this? i want to just replace the first letter in the last and first name with the char first and last
if you are trying to do what i think you are, you should consider using the apache commons-lang library, then look at:
WordUtils.capitalize
obviously, this is also open source, so for the best solution to your homework i'd take a look at the source code.
However, if i were writing it from scratch (and optimum performance wasn't the goal) here's how i would approach it:
public String capitalize(String input)
{
// 1. split on the negated 'word' matcher (regular expressions)
String[] words = input.toLowerCase().split("\\W");
StringBuffer end = new StringBuffer();
for (String word : words)
{
if (word.length == 0)
continue;
end.append(" ");
end.append(Character.toUpperCase(word.charAt(0)));
end.append(word.substring(1));
}
// delete the first space character
return end.deleteCharAt(0).toString();
}
While there's more efficient ways of doing this, you almost got it. You'd just need to concatenate the uppercase chars with the first and last name, bar the first character.
String newname = "" + l + last.subString(1) + " " + f + first.subString(1);
EDIT:
You could also use a string tokenizer to get the names as in:
StringTokenizer st = new StringTokenizer(Name);
String fullName = "";
String currentName;
while (st.hasMoreTokens()) {
/* add spaces between each name */
if(fullName != "") fullName += " ";
currentName = st.nextToken();
fullName += currentName.substring(0,0).toUpperCase() + currentName.substring(1);
}
String name = "firstname lastname";
//match with letter in beginning or a letter after a space
Matcher matcher = Pattern.compile("^\\w| \\w").matcher(name);
StringBuffer b=new StringBuffer();
while(matcher.find())
matcher.appendReplacement(b,matcher.group().toUpperCase());
matcher.appendTail(b);
name=b.toString();//Modified Name

Write a program that allows the user to enter a string and then prints the letters of the String separated by comma

The output is always a String, for example H,E,L,L,O,. How could I limit the commas? I want the commas only between letters, for example H,E,L,L,O.
import java.util.Scanner;
import java.lang.String;
public class forLoop
{
public static void main(String[] args)
{
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.next();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length(); i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
System.out.print(Str2);
}
}
Since this is homework I'll help you out a little without giving the answer:
If you want the output to only be inbetween letters IE: A,B,C instead of A,B,C, which is what I imagine you are asking about. Then you need to look at your for loop and check the boundary conditions.
The easiest way I see is :
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.nextLine();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length()-1; i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
Str2 = Str2 + Str1.charAt(Str1.length()-1);
System.out.println(Str2);
}
The output it will give is :
run:
Enter a string: Hello world
H,e,l,l,o, ,w,o,r,l,d
BUILD SUCCESSFUL (total time: 5 seconds)
Though I will highly recommend learning regular expression as suggested by #Roman. Till then this will do the trick. :)
Try regular expressions:
String input = scanner.next();
String output = input.replaceAll(".", "$0,");
With spaces it would be a bit easier since you don't need to abandon last 'odd' comma:
output = output.substring (0, ouput.length() - 2);
When you've figured out the loop-solution, you could try the following ;)
System.out.println(Arrays.toString("HELLO".toCharArray()).replaceAll("[\\[ \\]]", ""));
Just don't append the comma when the last item of the loop is to be appended. You have the item index by i and the string length by Str2.length(). Just do the primary school math with a lesser-than or a greater-than operator in an if statement.
The following snippet should be instructive. It shows:
How to use StringBuilder for building strings
How to process each char in a String using an explicit index
How to detect if it's the first/last iteration for special processing
String s = "HELLO";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (i == 0) { // first
sb.append("(" + ch + ")");
} else if (i == s.length() - 1) { // last
sb.append("<" + ch + ">");
} else { // everything in between
sb.append(Character.toLowerCase(ch));
}
}
System.out.println(sb.toString());
// prints "(H)ell<O>"

Categories