Taking Portions of a String - java

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

Related

How do i print the the first initial of a string and the last word of a string?

How do I print only the first letter of the first word and the whole word of the last? for example,
I will request username input like "Enter your first and last name" and then if I type my name like "Peter Griffin", I want to print only "P and Griffin". I hope this question make sense. Please, help. I'm a complete beginner as you can tell.
Here is my code:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter your first and last name");
String fname=scan.next();
}
The String methods trim, substring, indexof, lastindexof, and maybe split should get you going.
This should do the work (typed directly here, so syntax errors might be there)
String fname=scan.nextLine(); // or however you would read whole line
String parts=fname.split(" ");
System.out.printf("%s %s",parts[0].substring(0,1),parts[parts.length-1]);
What you have to do next:
Check if there actually at least 2 elements in parts array
Check if first element is actually at least 1 char (no empty parts)
Check if there is actually line to read
Do your next homework yourself, otherwise you will not anything
I recommand you to watch subString(1, x) and indexOf(" ") to cut from index 1 to first space.
or here a other exemple, dealing with lower and multi name :
String s = "peter griffin foobar";
String[] splitted = s.toLowerCase().split(" ");
StringBuilder results = new StringBuilder();
results.append(String.valueOf(splitted[0].charAt(0)).toUpperCase() + " ");
for (int i = 1; i < splitted.length; i++) {
results.append(splitted[i].substring(0, 1).toUpperCase() + splitted[i].substring(1)+" ");
}
System.out.println(results.toString());

Replace last two letters in Java

I am asking for help on this code that I am making, I want it to replace the last two letters. I am coding a program that will:
Replace four letter words with "FRED"
Replace the last two letters of a word that ends with "ed" to "id"
Finally, replace the first two letters if the word starts with "di" to "id"
I am having difficulty with the second stated rule, I know that for number 3 I can just use replaceFirst() and to use the length for the first rule, but I am not sure how to specifically swap the last two characters in the string.
Here is what I have so far:
package KingFred;
import java.util.Scanner;
public class KingFredofId2 {
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String king = input.nextLine();
String king22 = new String();
String king23 = new String();
if(king.length()==4)
{
System.out.println("FRED");
}
String myString = king.substring(Math.max(king.length() - 2, 0));
if (myString.equals("ed"))
{
king22 = king.replace("ed", "id");
System.out.println(king22);
}
if(true)
{
king23 = king.replace("di", "id");
System.out.println(king23);
}
}
I am new to Stack Overflow, so please let me know how I can make my questions a little more understandable if this one is not easily comprehended.
Thanks.
There may be a way to more optimally combine the regular expressions, but this will work.
\\b - word boundary (white space, punctuation,etc).
\\b(?:\\w){4}\\b - four letter word
ed\\b - word ending with ed
\\bdi - word starting with di
replaceAll(regex,b) - replace what regex matches with string b
String s =
"Bill charles among hello fool march good deed, dirt, dirty, divine dried freed died";
s = s.replaceAll("\\b(?:\\w){4}\\b", "FRED")
.replaceAll("ed\\b", "id")
.replaceAll("\\bdi", "id");
System.out.println(s);
prints
FRED charles among hello FRED march FRED FRED, FRED, idrty, idvine driid freid F
RED
This is the most simplest way I could think to solve the second case of replacing the last two characters.
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a line or a word: ");
String s = sc.nextLine();
//getting the length of entered string
int length = s.length();
//initializing a new string to hold the last two characters of the entered string
String extract = "";
//checking if length of entered string is more than 2
if (length > 2) {
//extracting the last two letters
extract = s.substring(length - 2);
//updating the original string
s = s.substring(0, length - 2);
}
//checking if the last two characters fulfil the condition for changing them
if (extract.equalsIgnoreCase("ed")) {
//if they do, concatenate "id" to the now updated original string
System.out.println(s + "id");
} else {
//or print the originally entered string
System.out.println(s + extract);
}
}
}
I believe the comments are giving enough explanation and further explanation is not needed.

Separating an unknown amount of hyphens in java?

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.

return the first word in any string (Java)

I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );

Checking string formats in Java?

having problems doing something for a class I'm taking, since I missed a class or two. (I know it's looked down on to 'do someone's homework,' but I'm not looking for that.)
The assignment is as follows:
Write a program to do the following:
Prompt for input of someone's first, middle, and last name as a single string (using any combination of upper and lowercase letters).
Check to make sure the name was entered in the correct format (3 names separated by spaces). If the input is not correct, continue to request the input again until the format is correct.
Capitalize only the first letters of each part of the name, and print out the revised name.
Print out the initials for that name.
Print out the name in the format of: Lastname, Firstname, MI.
The major problem I'm having is the second part of the assignment; I got the first part, and I'm fairly sure I can manage through the rest, after I get the second set up.
import java.util.*;
public class TestStrings
{
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
String name;
System.out.print("Enter your name as 'First Middle Last': ");
name = key.nextLine();
}
}
From what I've gathered, I need to use the string.split? I'm not sure how to go about this, though, since I need to check to make sure there are three spaces, that aren't just right next to each other or something, such as "John(three spaces)Doe". I assume it's going to be some kind of loop to check through the input for the name.
The catch 22, is that I can't use arrays, or StringTokenizer. I must use the substring method.
Any help would be appreciated. Thanks. :D
To point you in the right direction to find the first name(since you cant use arrays):
String firstName = input.substring(0, input.indexOf(" "));
This will get you a substring from the start to the first space. If you research the indexOf and substring methods you should be able to go from there.
Look at the matches method if you know how to use regex. If not think about indexOf and substring methods.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
You can use the substring and the indexOf functions of String class to get what you need.
String#indexOf: Get's the position of a String inside a String.
String#substring: Get's a substring contained in a String.
String s = "Luiggi Mendoza J.";
String x;
while(s.indexOf(" ") > 0) {
x = s.substring(0, s.indexOf(" "));
System.out.println(x);
s = s.substring(s.indexOf(" ") + 1);
}
x = s;
System.out.println(x);
The program output will be:
Luiggi
Mendoza
J.
Use a while loop to continuously check whether user entered a string that consists of 3 parts which are seperated via a single space character ' ', then use split() function to verify 3 parts of string. By using substring() as demonstrated here you can get names seperately:
public static void main ( String [] args )
{
String name = "";
boolean ok = false;
Scanner key = new Scanner( System.in );
while ( !ok )
{
System.out.print( "Enter your name as 'First Middle Last': " );
name = key.nextLine();
try
{
if ( name.split( " " ).length == 3 )
ok = true;
}
catch ( Exception e ){ }
}
if ( ok )
{
String firstName = name.substring(0, name.indexOf(" "));
String middleName = name.substring(firstName.length()+1,
name.lastIndexOf(" "));
String surname = name.substring(middleName.length()+firstName.length()+2,
name.length());
}
}
This works using Pattern/Matcher and regexs. Also guards against strings of length 1 when adjusting case.
private static String properCase(String str) {
return str.substring(0, 1).toUpperCase()
+ (str.length() >= 1 ? str.substring(1).toLowerCase() : "");
}
public static void main(String[] args) {
boolean found = false;
do {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name as 'First Middle Last': ");
Pattern p = Pattern.compile("\\s*(\\w+?)\\s(\\w+?)\\s(\\w+)+\\s*");
Matcher m = p.matcher(scanner.nextLine());
found = m.find();
if (found) {
String first = m.group(1);
String middle = m.group(2);
String last = m.group(3);
String revised = properCase(first) + " " + properCase(middle)
+ " " + properCase(last);
System.out.println(revised);
System.out
.printf("%s %s %s.\n", properCase(last),
properCase(first), middle.substring(0, 1)
.toUpperCase());
}
} while (!found);
}

Categories

Resources