Thanks for reading this. I'm currently making a phonebook project which required me to use only one array to store values. My question is how can you split a String inside of an array into two value? So I can search someone's name and get their name and number.
You can simply use the String#split method on any element of the array, whose delimiter can be any character. Here is an example where I chose : to be the delimiter.
String[] information = { "Castiel Li:123-456-7890" };
String[] args = information.split(":");
String name = args[0];
String phoneNumber = args[1];
If you have an array like the following:
String[] records = {"Bob, 1", "Mary, 2", "Castiel, 3"};
Then you can iterate over the record array in a loop and apply the String#split() method to each String object. In this case, the delimiter (character that separates tokes) in each string is the ',', so for a given String "name, number", you'd do:
String[] oneRecord = records[i].split(',');
Where oneRecord[i] would contain the two String objects "name" and "number"
You haven't given sample inputs and outputs. But I think you are saying that you are storing the phone book in a single dimension array like following:
String[] array = {"Abc123", "xyz234", "pqr343"};
You can try something like following:
String phone1 = array[0].replaceAll("[^0-9]", "");
String name1 = array[0].replaceAll("[0-9]", "");
System.out.println(name1 + " " + phone1);
Something like this perhaps that use str.split()
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String phoneBook[] = new String[2];
phoneBook[0] = "John 1234567";
phoneBook[1] = "Max 2345678";
System.out.println(Arrays.toString(phoneBook));
for(String contact : phoneBook)
System.out.println("Name: " + contact.split(" ")[0] + " Phone Number: " + contact.split(" ")[1]);
}
}
Output:
[John 1234567, Max 2345678]
Name: John Phone Number: 1234567
Name: Max Phone Number: 2345678
Try it here!
Related
For example the name Donald trump (12 character) brings up the error string index out of range 7 (where the space is found) even though the name Donald trump is longer.
package test;
import javax.swing.JOptionPane;
public class Usernamesubstring {
public static void main(String[] args) {
String fullname = JOptionPane.showInputDialog("What is your full name");
int breakbetween = fullname.lastIndexOf(" ");
String firstnamess = fullname.substring(breakbetween - 3, breakbetween);
int length = fullname.length();
String lastnamess = fullname.substring(length - 3, length);
String firstnamec = firstnamess.substring(0, 0);
String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 );
firstnamec = firstnamec.toUpperCase();
lastnamec = lastnamec.toUpperCase();
String firstname = firstnamess.substring(1,3);
String lastname = firstnamess.substring(1,3);
firstname = firstnamec + firstname;
lastname = lastnamec + lastname;
System.out.println(firstname + lastname);
}
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1963)
at test.Usernamesubstring.main(Usernamesubstring.java:14)
You've made it more complicated than it needs to be. A simple solution can be made using String.split (which divides a string into an array of smaller strings based on a delimiter, e.g. "Donald Trump".split(" ") == {"Donald", "Trump"})
Full Code
class Usernamesubstring // change that since it no longer uses substrings
{
public static void main (String[] args)
{
String fullName = "Donald Trump";
String[] parts = fullName.split(" ");
String firstName = parts[0]; // first item before the space
String lastName = parts[parts.length - 1]; // last item in the array
System.out.println(firstName + " " + lastName);
}
}
sometimes independent of your indexes
String fullName = "Donald Trump";
String[] result = fullName.split (" ");
in result you will find now
result [0] ==> Donald
result [1] ==> Trump
isn't that a little easier for your project?
Your error shoul be in the line String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 ); as lastnamess is a string of lenght 3 from fullname.substring(length - 3, length); and breakbetween is greater then 3 for "Donald Trump", where space is character 6.
You should simpify your code a bit, it makes it easier to read and find the problems.
tl;dr: The exception occurs when you try to access a String at an index which exceeds it's length or is just not contained in the string (negative values).
Regarding your approach: It's usually not a good idea to prompt a name in full because people tend to input weird stuff or mix up the order. Better prompt for first and last name separately.
Assuming someone input his name with Firstname Lastname you wouldn't have to make such a substring mess, Java has some nice features:
String name = "Mario Peach Bowser";
name = name.trim();
String[] parts = name.split(" ");
String lastname = parts[parts.length-1];
String firstname = name.replace(lastname, "").trim();
System.out.println("Hello "+firstname+", your last name is: "+lastname);
In this case I am using the trim() function to remove whitespaces at the start and end and just split the string when a white space occurs. Since people can have some middle names and stuff, I just replace the last name out of the raw input string, call trim() on it again and you have everything extracted.
If you really want a substring approach, the following would work:
String lastname = name.substring(name.lastIndexOf(" ")).trim();
String firstname = name.substring(0,name.lastIndexOf(" ")).trim();
You usually don't store the index variables. But each variant would need some sort of error check, you can either use try{} and catch() or check the String before parsing.
Only these lines are required.
String[] nameArr = fullname.split(" ");
String lastN = nameArr[nameArr.length - 1];
int lastIndexOf = fullname.lastIndexOf(lastN);
String firstN = fullname.substring(0, lastIndexOf);
System.out.println(firstN + " " + lastN);
I'm writing out a piece of a code that where I am trying to split up the user's input into 3 different arrays, by using the spaces in-between the values the user has entered. However, everytime i run the code i get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Substring.main(Substring.java:18)
Java Result: 1
I have tried to use a different delimiter when entering the text and it has worked fine, e.g. using a / split the exact same input normally, and did what i wanted it to do thus far.
Any help would be appreciated!
Here's my code if needed
import java.util.Scanner;
public class Substring{
public static void main(String[]args){
Scanner user_input = new Scanner(System.in);
String fullname = ""; //declaring a variable so the user can enter their full name
String[] NameSplit = new String[2];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
fullname = user_input.next(); //saving the user's name in the string fullname
NameSplit = fullname.split(" ");//We are splitting up the value of fullname every time there is a space between words
FirstName = NameSplit[0]; //Putting the values that are in the array into seperate string values, so they are easier to handle
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname); //outputting the user's orginal input
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);//outputting the last name first, then the first name, then the middle name
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Split is a regular expression, you can look for one or more spaces (" +") instead of just one space (" ").
String[] array = s.split(" +");
Or you can use Strint Tokenizer
String message = "MY name is ";
String delim = " \n\r\t,.;"; //insert here all delimitators
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You have made mistakes at following places:
fullname = user_input.next();
It should be nextLine() instead of just next() since you want to read the complete line from the Scanner.
String[] NameSplit = new String[2];
There is no need for this step as you are doing NameSplit = user_input.split(...) later but it should be new String[3] instead of new String[2] since you are storing three entries i.e. First Name, Middle Name and the Last Name.
Here is the correct program:
class Substring {
public static void main (String[] args) throws java.lang.Exception {
Scanner user_input = new Scanner(System.in);
String[] NameSplit = new String[3];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
String fullname = user_input.nextLine();
NameSplit = fullname.split(" ");
FirstName = NameSplit[0];
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname);
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Output:
Enter your full name (First Middle Last): John Mayer Smith
Smith, John Mayer
John
java.util.Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
hence even though you entered 'Elvis John Presley' only 'Elvis' is stored in the fullName variable.
You can use BufferedReader to read full line:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
fullname = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
or you can change the default behavior of scanner by using:
user_input.useDelimiter("\n"); method.
The exception clearly tells that you are exceeding the array's length. The index 2 in LastName = NameSplit[2] is out of array's bounds. To get rid of the error you must:
1- Change String[] NameSplit = new String[2] to String[] NameSplit = new String[3] because the array length should be 3.
Read more here: [ How do I declare and initialize an array in Java? ]
Up to here the error is gone but the solution is not correct yet since NameSplit[1] and NameSplit[2] are null, because user_input.next(); reads only the first word (*basically until a whitespace (or '\n' if only one word) is detected). So:
2- Change user_input.next(); to user_input.nextLine(); because the nextLine() reads the entire line (*basically until a '\n' is detected)
Read more here: [ http://www.cs.utexas.edu/users/ndale/Scanner.html ]
I was wondering if someone can show me how to use the format method for Java Strings.
For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
System.out.println(String.format("%-20s= %s" , "label", "content" ));
Where %s is a placeholder for you string.
The '-' makes the result left-justified.
20 is the width of the first string
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
If you want a minimum of 4 characters, for instance,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.
#Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
For decimal values you can use DecimalFormat
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
and output will be:
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
I was wondering if someone can show me how to use the format method for Java Strings.
For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
System.out.println(String.format("%-20s= %s" , "label", "content" ));
Where %s is a placeholder for you string.
The '-' makes the result left-justified.
20 is the width of the first string
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
If you want a minimum of 4 characters, for instance,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.
#Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
For decimal values you can use DecimalFormat
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
and output will be:
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
I want to make strings like "a b c" to "prefix_a prefix_b prefix_c"
how to do that in java?
You can use the String method: replaceAll(String regex,String replacement)
String s = "a xyz c";
s = s.replaceAll("(\\w+)", "prefix_$1");
System.out.println(s);
You may need to tweek the regexp to meet your exact requirements.
Assuming a split character of a space (" "), the String can be split using the split method, then each new String can have the prefix_ appended, then concatenated back to a String:
String[] tokens = "a b c".split(" ");
String result = "";
for (String token : tokens) {
result += ("prefix_" + token + " ");
}
System.out.println(result);
Output:
prefix_a prefix_b prefix_c
Using a StringBuilder would improve performance if necessary:
String[] tokens = "a b c".split(" ");
StringBuilder result = new StringBuilder();
for (String token : tokens) {
result.append("prefix_");
result.append(token);
result.append(" ");
}
result.deleteCharAt(result.length() - 1);
System.out.println(result.toString());
The only catch with the first sample is that there will be an extraneous space at the end of the last token.
hope I'm not mis-reading the question. Are you just looking for straight up concatenation?
String someString = "a";
String yourPrefix = "prefix_"; // or whatever
String result = yourPrefix + someString;
System.out.println(result);
would show you
prefix_a
You can use StringTokenizer to enumerate over your string, with a "space" delimiter, and in your loop you can add your prefix onto the current element in your enumeration. Bottom line: See StringTokenizer in the javadocs.
You could also do it with regex and a word boundary ("\b"), but this seems brittle.
Another possibility is using String.split to convert your string into an array of strings, and then loop over your array of "a", "b", and "c" and prefix your array elements with the prefix of your choice.
You can split a string using regular expressions and put it back together with a loop over the resulting array:
public class Test {
public static void main (String args[]) {
String s = "a b c";
String[] s2 = s.split("\\s+");
String s3 = "";
if (s2.length > 0)
s3 = "pattern_" + s2[0];
for (int i = 1; i < s2.length; i++) {
s3 = s3 + " pattern_" + s2[i];
}
System.out.println (s3);
}
}
This is C# but should easily translate to Java (but it's not a very smart solution).
String input = "a b c";
String output (" " + input).Replace(" ", "prefix_")
UPDATE
The first solution has no spaces in the output. This solution requires a place holder symbol (#) not occuring in the input.
String output = ("#" + input.Replace(" ", " #")).Replace("#", "prefix_");
It's probably more efficient to use a StringBuilder.
String input = "a b c";
String[] items = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (String item in items)
{
sb.Append("prefix_");
sb.Append(item);
sb.Append(" ");
}
sb.Length--;
String output = sb.ToString();