Good day, guys,
I'm working on a program which requires me to input a name (E.g Patrick-Connor-O'Neill). The name can be composed of as many names as possible, so not necessarily restricted to solely 3 as seen in the example above.But the point of the program is to return the initials back so in this case PCO. I'm writing to ask for a little clarification. I need to separate the names out from the hyphens first, right? Then I need to take the first character of the names and print that out?
Anyway, my question is basically how do I separate the string if I don't know how much is inputted? I get that if it's only like two terms I would do:
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
I did attempt to do the code, and all I have so far is:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
}
}
}
I'm taking a crash course in programming, so easy concepts are hard for me.Thanks for reading!
You don't need to split it a second time. By doing String[] x = input.split("-"); you have an Array of Strings. Now you can iterate over them which you already do with the enhanced for loop. It should look like this
String[] x = input.split("-");
String initials = "";
for (String name : x) {
initials += name.charAt(0);
}
System.out.println(initials);
Here are some Java Docs for the used methods
String#split
String#charAt
Assignment operator +=
You can do it without splitting the string by using String.indexOf to find the next -; then just append the subsequent character to the initials:
String initials = "" + input.charAt(0);
int next = -1;
while (true) {
next = input.indexOf('-', next + 1);
if (next < 0) break;
initials += input.charAt(next + 1);
}
(There are lots of edge cases not handled here; omitted to get across the main point of the approach).
In your for-each loop append first character of all the elements of String array into an output String to get the initials:
String output = "";
for(String i : x) {
output = output + y.charAt(0);
}
This will help.
public static void main(String[] args) {
String output = "";
String input = "Patrick-Connor-O'Neil-Saint-Patricks-Day";
String[] brokenInput = input.split("-");
for (String temp : brokenInput) {
if (!temp.equals(""))
output = output + temp.charAt(0);
}
System.out.println(output);
}
You could totally try something like this (a little refactor of your code):
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = "";
System.out.println("What's your name?");
input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
System.out.println(y);
}
}
}
I think it's pretty easy and straightforward from here if you want to simply isolate the initials. If you are new to Java make sure you use a lot of System.out since it helps you a lot with debugging.
Good coding.
EDIT: You can use #Mohit Tyagi 's answer with mine to achieve the full thing if you are cheating :P
This might help
String test = "abs-bcd-cde-fgh-lik";
String[] splitArray = test.split("-");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < splitArray.length; i++) {
stringBuffer.append(splitArray[i].charAt(0));
}
System.out.println(stringBuffer);
}
Using StringBuffer will save your memory as, if you use String a new object will get created every time you modify it.
Related
For my Java homework I need to create a script that returns the first word within a string, and, as a part two, I need to also return the second word. I'm currently working on the first part, and I think I'm close, but I'm also wondering if I am over complicating my code a bit.
public static void statements(){
Scanner userInput = new Scanner(System.in);
char [] sentenceArray;
String userSentence;
char sentenceResult;
System.out.print("Enter a complete sentence: ");
userSentence = userInput.nextLine();
for(int x = 0; x < userSentence.length(); x++){
sentenceResult = userSentence.charAt(x);
sentenceArray = new char[userSentence.length()];
sentenceArray[x] = sentenceResult;
if(sentenceArray[x] != ' '){
System.out.print(sentenceArray[x]);
//break; This stops the code at the first letter due to != ' '
}
}
}
I think I've nearly got it. All I need to get working, for the moment, is the for loop to exit once it recognizes there is a space, but it prints out the entire message regardless. I'm just curious if this can be done a little simpler, as well as maybe a hint of what I could do instead, or how to finish.
Edit: I was able to get the assignment completed by using the split method. This is what it now looks like
public static void statements(){
Scanner userInput = new Scanner(System.in);
String userSentence;
System.out.print("Enter a complete sentence: ");
userSentence = userInput.nextLine();
String [] sentenceArray = userSentence.split(" ");
System.out.println(sentenceArray[0]);
System.out.println(sentenceArray[1]);
}
}
As it is your homework, I would feel bad to give you code and resolve it for you.
Seems like you really overcomplicated that, and you are aware, so it's good sign.
I need to create a script that returns the first word within a string,
and, as a part two, I need to also return the second word
So, you have a String object, then check yourself the methods of that class.
It is possible to solve it in 2 lines of code, but:
you must be aware of one special method of String class, the most useful will be one that could somehow split the string for you
you need to have some knowledge about java regular expressions - words are separated by space
after you split the string, you should get an array, accessing first and second element by index of an array will be sufficient
Personally, I think you are overthinking it. Why not read in the whole line and split the string by whitespaces? This isn't a complete solution, just a suggestion for how you can get the words.
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a complete sentence: ");
try {
String userSentence = reader.readLine();
String[] words = userSentence.split(" ");
System.out.println(words[0]);
System.out.println(words[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here's how I'd do it. Why not return all the words?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Add something descriptive here.
* User: MDUFFY
* Date: 8/31/2017
* Time: 4:58 PM
* #link https://stackoverflow.com/questions/45989774/am-i-over-complicating-a-simple-solution
*/
public class WordSplitter {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(String.format("Sentence: %s", arg));
List<String> words = getWords(arg);
System.out.println(String.format("# words : %d", words.size()));
System.out.println(String.format("words : %s", words));
}
}
public static List<String> getWords(String sentence) {
List<String> words = new ArrayList<>();
if ((sentence != null) && !"".equalsIgnoreCase(sentence.trim())) {
sentence = sentence.replaceAll("[.!?\\-,]", "");
String [] tokens = sentence.split("\\s+");
words = Arrays.asList(tokens);
}
return words;
}
}
When I run it with this input on the command line:
"The quick, agile, beautiful fox jumped over the lazy, fat, slow dog!"
Here's the result I get:
Sentence: The quick, agile, beautiful fox jumped over the lazy, fat, slow dog!
# words : 12
words : [The, quick, agile, beautiful, fox, jumped, over, the, lazy, fat, slow, dog]
Process finished with exit code 0
I would like to split a line which might look like this:
6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0
The first value is x the second y.
Now i would like to have as a result two Lists ListX<Integer> and ListY<Double>.
I have tried doing it char by char. Where you can search for ':' and then go back and front to get the number. But there must be a faster way. Especially regarding on the lenght of the string which can get really big. Do You have any idea?
Thanks
You can try using String.split():
String test = "6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0";
String[] splitString1 = test.split(" ");
String[] splitString2 = null;
for(String a : splitString1)
{
splitString2 = a.split(":");
System.out.println(splitString2[0]);
System.out.println(splitString2[1]);
//push splitString2[0] to x
//push splitString2[1] to y
}
Here is the complete code which does what you are thinking to do
import java.util.*;
public class IntegerDoubleExtractor{
public static void main(String []args){
String test = "6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0";
List<Integer> x = new ArrayList<Integer>();
List<Double> y = new ArrayList<Double>();
for(String xy : test.split(" ")) {
String xys[] = xy.split(":");
x.add(Integer.parseInt(xys[0]));
y.add(Double.parseDouble(xys[1]));
}
System.out.println(x);
System.out.println(y);
}
}
You can also use a Scanner and you won't need intermediate Strings or arrays in the process:
Scanner scanner = new Scanner(str);
scanner.useDelimiter(Pattern.compile("[:\\s]"));
while (scanner.hasNext()) {
listX.add(scanner.nextInt());
listY.add(scanner.nextDouble());
}
I am very new to Java and as a starter I have been offered to try this at home.
Write a program that will find out number of occurences of a smaller string in a bigger string as a part of it as well as an individual word.
For example,
Bigger string = "I AM IN AMSTERDAM", smaller string = "AM".
Output: As part of string: 3, as a part of word: 1.
While I did nail the second part (as a part of word), and even had my go at the first one (searching for the word as a part of the string), I just don't seem to figure out how to crack the first part. It keeps on displaying 1 for me with the example input, where it should be 3.
I have definitely made an error- I'll be really grateful if you could point out the error and rectify it. As a request, I am curious learner- so if possible (at your will)- please provide an explanation as to why so.
import java.util.Scanner;
public class Program {
static Scanner sc = new Scanner(System.in);
static String search,searchstring;
static int n;
void input(){
System.out.println("What do you want to do?"); System.out.println("1.
Search as part of string?");
System.out.println("2. Search as part of word?");
int n = sc.nextInt();
System.out.println("Enter the main string"); searchstring =
sc.nextLine();
sc.nextLine(); //Clear buffer
System.out.println("Enter the search string"); search = sc.nextLine();
}
static int asPartOfWord(String main,String search){
int count = 0;
char c; String w = "";
for (int i = 0; i<main.length();i++){
c = main.charAt(i);
if (!(c==' ')){
w += c;
}
else {
if (w.equals(search)){
count++;
}
w = ""; // Flush old value of w
}
}
return count;
}
static int asPartOfString(String main,String search){
int count = 0;
char c; String w = ""; //Stores the word
for (int i = 0; i<main.length();i++){
c = main.charAt(i);
if (!(c==' ')){
w += c;
}
else {
if (w.length()==search.length()){
if (w.equals(search)){
count++;
}
}
w = ""; // Replace with new value, no string
}
}
return count;
}
public static void main(String[] args){
Program a = new Program();
a.input();
switch(n){
case 1: System.out.println("Total occurences: " +
asPartOfString(searchstring,search));
case 2: System.out.println("Total occurences: " +
asPartOfWord(searchstring,search));
default: System.out.println("ERROR: No valid number entered");
}
}
}
EDIT: I will be using the loop structure.
A simpler way would be to use regular expressions (that probably defeats the idea of writing it yourself, although learning regexes is a good idea because they are very powerful: as you can see the core of my code is 4 lines long in the countMatches method).
public static void main(String... args) {
String bigger = "I AM IN AMSTERDAM";
String smaller = "AM";
System.out.println("Output: As part of string: " + countMatches(bigger, smaller) +
", as a part of word: " + countMatches(bigger, "\\b" + smaller + "\\b"));
}
private static int countMatches(String in, String regex) {
Matcher m = Pattern.compile(regex).matcher(in);
int count = 0;
while (m.find()) count++;
return count;
}
How does it work?
we create a Matcher that will find a specific pattern in your string, and then iterate to find the next match until there is none left and increment a counter
the patterns themselves: "AM" will find any occurrence of AM in the string, in any position. "\\bAM\\b" will only match whole words (\\b is a word delimiter).
That may not be what you were looking for but I thought it'd be interesting to see another approach. An technically, I am using a loop :-)
Although writing your own code with lots of loops to work things out may execute faster (debatable), it's better to use the JDK if you can, because there's less code to write, less debugging and you can focus on the high-level stuff instead of the low level implementation of character iteration and comparison.
It so happens, the tools you need to solve this already exist, and although using them requires knowledge you don't have, they are elegant to the point of being a single line of code for each method.
Here's how I would solve it:
static int asPartOfString(String main,String search){
return main.split(search, -1).length - 1;
}
static int asPartOfWord(String main,String search){
return main.split("\\b" + search + "\\b", -1).length - 1
}
See live demo of this code running with your sample input, which (probably deliberately) contains an edge case (see below).
Performance? Probably a few microseconds - fast enough. But the real benefit is there is so little code that it's completely clear what's going on, and almost nothing to get wrong or that needs debugging.
The stuff you need to know to use this solution:
regex term for "word boundary" is \b
split() takes a regex as its search term
the 2nd parameter of split() controls behaviour at the end of the string: a negative number means "retain blanks at end of split", which handle the edge case of the main string ending with the smaller string. Without the -1, a call to split would throw away the trailing blank in this edge case.
You could use Regular Expressions, try ".*<target string>.*" (Replace target string with what you are searching for.
Have a look at the Java Doc for "Patterns & Regular Expressions"
To search for the occurrences in a string this could be helpful.
Matcher matcher = Pattern.compile(".*AM.*").matcher("I AM IN AMSTERDAM")
int count = 0;
while (matcher.find()) {
count++;
}
Here's an alternative (and much shorter) way to get it to work using Pattern and Matcher,or more commonly known as regex.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountOccurances {
public static void main(String[] args) {
String main = "I AM IN AMSTERDAM";
String search = "AM";
System.out.printf("As part of string: %d%n",
asPartOfString(main, search));
System.out.printf("As part of word: %d%n",
asPartOfWord(main, search));
}
private static int asPartOfString(String main, String search) {
Matcher m = Pattern.compile(search).matcher(main);
int count = 0;
while (m.find()) {
count++;
}
return count;
}
private static int asPartOfWord(String main, String search) {
// \b - A word boundary
return asPartOfString(main, "\\b" + search + "\\b");
}
}
Output:
As part of string: 3
As part of word: 1
For the first part of your Exercise this should work:
static int asPartOfWord(String main, String search) {
int count = 0;
while(main.length() >= search.length()) { // while String main is at least as long as String search
if (main.substring(0,search.length()).equals(search)) { // if String main from index 0 until exclusively search.length() equals the String search, count is incremented;
count++;
}
main = main.substring(1); // String main is shortened by cutting off the first character
}
return count;
You may think about the way you name variables:
static String search,searchstring;
static int n;
While search and searchstring will tell us what is meant, you should write the first word in lower case, every word that follows should be written with the first letter in upper case. This improves readability.
static int n won't give you much of a clue what it is used for if you read your code again after a few days, you might use something more meaningful here.
static String search, searchString;
static int command;
This question already has answers here:
Reversing characters in each word in a sentence - Stack Implementation
(6 answers)
Closed 9 years ago.
I am supposed to write a code that reads a sentence from the user and prints the characters of the words in the sentence backwards. It should include a helper method that takes a String as a parameter and returns a new String with the characters reversed. The individual words are reversed, for example the sentence "Hi dog cat". would print "iH god tac". I can make the entire sentence reverse but i cant figure out how to reverse individual words. Thanks! Also, i know how to return the String once i have found it, but i just cant get the right string
import java.util.Scanner;
import java.util.Stack;
public class ReverseStack
{
public static void main(String[] args)
{
String sentence;
System.out.println("Enter a sentence: ");
Scanner scan = new Scanner(System.in);
sentence = scan.nextLine();
String k = PrintStack(sentence);
}
private static String PrintStack(String sentence)
{
String reverse;
String stringReversed = "";
Stack<String> stack= new Stack<String>();
sentence.split(" ");
for(int i=0;i<sentence.length(); i++)
{
stack.push(sentence.substring(i, i+1));
}
while(!stack.isEmpty())
{
stringReversed += stack.pop();
}
System.out.println("Reverse is: " + stringReversed);
return reverse;
}
}
I will type an expatiation so you can still get the experience of writing the code, rather than me just giving you the code.
First create a Stack of Characters. Then use add each character in the String to the Stack, starting with the first char, then the second, and so on. Now either clear the String or create a new String to store the reversed word. Finally, add each character from the Stack to the String. This will pull the last character off first, then the second to last, and so on.
Note: I believe you have to use the Character wrapper class, rather than the primitive char; I may be incorrect about that though.
If you aren't familiar with how Stacks work, here is a nice interactive tool to visualize it: http://www.cise.ufl.edu/~sahni/dsaaj/JavaVersions/Stacks/AbstractStack/AbstractStack.htm
Change:
Stack<String> stack = new Stack<String>();
to be
Stack<Character> stack = new Stack<Character>();
and refactor your methods code as necessary; i.e.
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
I did it with a different kind of stack, but I suspect this might help
private static String reverseWord(String in) {
if (in.length() < 2) {
return in;
}
return reverseWord(in.substring(1)) + in.substring(0, 1);
}
private static String reverseSentence(String in) {
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(in);
while (st.hasMoreTokens()) {
if (sb.length() > 0)
sb.append(' ');
sb.append(reverseWord(st.nextToken()));
}
return sb.toString();
}
public static void main(String[] args) {
String sentence = "Hi dog cat";
String expectedOutput = "iH god tac";
System.out.println(expectedOutput
.equals(reverseSentence(sentence)));
}
Outputs
true
I am working on an assignment which is confusing to me. It requires me to write a method called processName() that accepts a Scanner for the console as a parameter and prompts the user to enter a full name, then prints the last name first and then the first name last. For instance, if I enter "Sammy Jankins", it would return "Jankins, Sammy".
My plan is to go through the string with a for loop, find an empty space, and create two new strings out of it—one for the first and last name each. However, I am not sure if this is the right path and how to exactly do this. Any tips would be appreciated, thanks.
Here is what I have so far:
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String name = inputScanner.next();
System.out.println();
int n = name.length();
String tempFirst;
for (int i = 0; i <= name.length()-1; i++) {
// Something that checks the indiviual characters of each string to see of " "exists
// Somethow split that String into two others.
}
}
}
Why don't you simply use String#split?
I won't solve this for you, but here what you should do:
split according to spaces.
Check if the size of the array is 2.
If so, print the second element then the first.
Tip: Viewing the API can save a lot of efforts and time.
Why not just to say:
String[] parts = name.split("\\s+");
String formattedName = parts[1] + ", " + parts[0];
I am leaving it for you as an exercise to support names that contain more than 2 words, for example "Juan Antonio Samaranch" that should be formatted as "Samaranch, Juan Antonio".
Using StringTokenizer will be more easier. Refer http://www.mkyong.com/java/java-stringtokenizer-example/ for example.
You can replace for loop with the following code:
int spaceIdx = name.indexOf(' '); // or .lastIndexOf(' ')
if (spaceIdx != -1) {
int nameLength = name.length();
System.out.println(name.substring(spaceIdx + 1) + ", " + name.substring(0, spaceIdx));
} else {
// handle incorrect input
}
I think you should also consider such inputs - Homer J Simpson
1.Use the StringTokenizer to split the string .This will be very helpful when you are trying to split the string.
String arr[]=new String[2]; int i=0; StringTokenizer str=new StringTokenizer(StringToBeSplited,"");
while(str.hasMoreTokens()){
arr[i++]=new String(str.nextToken());
}
System.out.println(arr[1]+" "+arr[0]);
That's all