if I have a String:
String str = "Hello, World!";
how can I get index of a key word:
int begin_index = str.GetKeywordIndex("World").GetBeginIndex();
int end_index = str.GetkeyWordIndex("World").GetEndIndex();
System.out.println("keyword World begin at:" + begin_index + "end: " + end_index);
// keyword World begin at: 7, end: 11
ps: I don't want to use for loop iterate String, because it's too slow
int begin_index = str.undexOf("World");
int end_index = begin_index+"World".length();
System.out.println("keyword World begin at:" + begin_index + "end: " + end_index);
Related
Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.
After doing some research it seems I can do this with the Split method, but we've not learned that yet.
The thing is I've worked out the code and it seems to work when spaces
and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:
when the name entered is simply: Harry Smith
java.lang.StringIndexOutOfBoundsException: String index out of range: -7
and
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
when the name is Sarah
This is my code, but I'm not sure how to fix it:
public class Names {
public static String lastNameFirst(String name) {
int firstIndex = name.indexOf(" ");
int secondIndex = name.indexOf(" ", firstIndex + 1);
String firstName = name.substring(0, name.indexOf(" "));
String middleName = name.substring(firstIndex + 1, secondIndex);
String lastName = name.substring(secondIndex + 1);
String result = "";
result = lastName + ", " + firstName + " " + middleName;
return result;
}
}
Thanks in advance!!
using split and a switch would be a lot easier
String name = "Mary Jane Lee";
String arr[] = name.split (" ");
switch (arr.length) {
case 1:
System.out.println(name);
break;
case 2:
System.out.println(arr[1] + ", " + arr[0]);
break;
default:
System.out.println(arr[2] + ", " + arr[0] + " " + arr[1]);
}
A more robust way is to use lastIndexOf to find the last space:
int lastSpace = name.lastIndexOf(' ');
if (lastSpace != -1) {
String lastName = name.substring(lastSpace + 1);
String partBeforeLastName = name.substring(0, lastSpace);
return lastName + ", " + partBeforeLastName;
} else {
return name;
}
You don't actually really care about the other space (if it's there at all), since the first and middle names stay in the same relative order.
(Generally, there are lots of falsehoods that programmers believe about names; but let's put those aside for the purpose of the exercise.)
Your code assumes that the input String contains at least two spaces. When that assumption is wrong (as in the inputs "Harry Smith" and "Sarah"), you get an exception.
You must check whether firstIndex and secondIndex are positive before using their values.
The problem is that your code excepts that there are 3 names. It does not handle when there are less names.
public static String lastNameFirst(String name)
{
int firstIndex = name.indexOf(" ");
if ( firstIndex >= 0 )
{
int secondIndex = name.indexOf(" ", firstIndex + 1 );
String firstName = name.substring(0, firstIndex);
if ( secondIndex >= 0 ) // we have 3 names
{
String middleName = name.substring(firstIndex + 1, secondIndex);
String lastName = name.substring(secondIndex + 1);
return lastName + ", " + firstName + " " + middleName;
}
else // we have 2 names
{
String lastName = name.substring(firstIndex + 1);
return lastName + ", " + firstName;
}
}
else // have only one name
return name;
}
Should worth trying lastIndexOf(), too:
public static String lastNameFirst(String name)
{
int lastIndex = name.lastIndexOf(" ");
if ( lastIndex >= 0 ) // have at least 2 names
{
String firstNames = name.substring(0,lastIndex);
String lastName = name.substring(lastIndex + 1);
return lastName + ", " + firstNames;
}
}
else // have only one name
return name;
}
Also, could try a different approach, split the name into an array, something like this:
public static String lastNameFirst(String name)
{
String[] parts = name.split(" ");
switch ( parts.length )
{
case 1:
return name;
case 2:
return parts[1] + ", " + parts[0];
case 3:
return parts[2] + ", " + parts[0] + " " + parts[1];
}
}
So my requirement is to display a message showing yours and your friend's initials in lower case (ie. "mf and js are friends").
Here's my code
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
System.out.println( myFullName.toLowerCase().charAt(0)
+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
The output I get is
199 and js are friends.
myFullName.toLowerCase().charAt(0) + myFullName.toLowerCase().charAt(7)
are working on ascii integer value and hence 199
The reason strings addition works for the second name is because that is part of the string formed due to this:
+ " and "
Quick fix, add an empty string at start
System.out.println("" + myFullName.toLowerCase().charAt(0)
+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
System.out.println( "" + myFullName.toLowerCase().charAt(0) + myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
Append the blank string to convert it to String and then it will start doing concanetation . As '+' is overloaded operator it is doing addition till it encounters String.
You can use following code :
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
String[] arrMyFullName = myFullName.toLowerCase().split(" ");
String[] arrFriendsFullName = friendsFullName.toLowerCase().split(" ");
String message = "";
for(String s : arrMyFullName)
message += s.charAt(0);
message += " and ";
for(String s : arrFriendsFullName)
message += s.charAt(0);
message += " are friends.";
System.out.println( message );
Above code also work if name is more than 2 words.
Try:
System.out.println( "" + myFullName.toLowerCase().charAt(0)
+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
With this one you can have any name of friends. Instead of correcting the index which differs for each name.
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
String[] myNameSplit = myFullName.split(" ");
String myFirstInitial = String.valueOf(myNameSplit[0].charAt(0));
String myLastInitial = String.valueOf(myNameSplit[1].charAt(0));
String[] myFriendNameSplit = friendsFullName.split(" ");
String myFriendFirstInitial = String.valueOf(myFriendNameSplit[0].charAt(0));
String myFriendLastInitial = String.valueOf(myFriendNameSplit[1].charAt(0));
System.out.println(myFirstInitial+myLastInitial + " and " + myFriendFirstInitial+myFriendLastInitial+ " are friends");
It is adding ASCII value of d and c in output to avoid that do as following.
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
System.out.println( myFullName.toLowerCase().charAt(0)
+""+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
I'm starting with this String:
"NAME-RAHUL KUMAR CHOUDHARY ADDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412"
I want to split the name and address, and print it like this:
NAME:RAHUL KUMAR CHOUDHARY , DDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412. like this
This is what I have so far:
String str_colArow3 = colArow3.getContents();
//Display the cell contents
System.out.println("Contents of cell Col A Row 3: \""+str_colArow3 + "\"");
if(str_colArow3.contains("NAME"))
{
}
else if(str_colArow3.contains("ADDRESS"))
{
}
String string = "NAME-RAHUL KUMAR CHOUDHARY ADDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412";
String[] parts = string.split("-");
string = "Name: " + parts[1].substring(0, parts[1].length() - 7)
+ "\nAdress: " + parts[2] + " - " + parts[3]
+ "\nPin Code: " + parts[5];
Something like this. Check out the split() method for strings, your string is a bit poorly formatted to use this, though. You have to adjust for your own needs.
Edit: Better way to do this, with different string input.
String string = "RAHUL KUMAR CHOUDHARY:RAJDHANWAR:GIRIDIH:JHARKHAND:825412";
String[] parts = string.split(":");
string = "Name: " + parts[0] + "\n"
+ "Address: " + parts[1] + "\n"
+ "District: " + parts[2] + "\n"
+ "State: " + parts[3] + "\n"
+ "Pin Code: " + parts[4] + "\n";
I am making a programming to print the following
user inputs name like so --> first middle last
prints:
FML
Variation one: LAST, First M.
Variation two: Last, First Middle
Now, I need an if statement so that if just a first name is entered it says "error, incorrect input"
I coded this horribly and extremely unconventional, but hey, this is the first thing I've ever programmed before, so I guess we all start somewhere.
import java.util.Scanner;
public class name {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
//Declares length of entire name
int nameLength = fullName.length();
//Declares int where first space is
int a = fullName.indexOf(" ");
//Declares int where second space is
int b = fullName.lastIndexOf(" ");
//If they equal each other, then there is only one space
if ( a == b )
{
firstName = fullName.substring(0,a);
lastName = fullName.substring(a+1,nameLength);
String firstNameInitial = firstName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
firstName = fullName.substring(0,a);
lastName = fullName.substring(b+1,nameLength);
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a));
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a));
}
//If a < b then it will notice a middle name exists due to multiple spaces
else if ( a < b )
{
firstName = fullName.substring(0,a);
middleName = fullName.substring(a+1,b);
lastName = fullName.substring(b+1,nameLength);
String firstNameInitial = firstName.substring(0,1);
String middleNameInitial = middleName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + middleNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
//MNIC = Middle Name Initial Capitalized
String MNIC = middleNameInitial.toUpperCase();
//MNIMFC = Middle Name Initial Minus First Character
String MNIMFC = middleName.substring(1, middleName.length());
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + middleNameInitial.toUpperCase() + "." );
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + MNIC + MNIMFC);
}
}
}
You can use the String.split() function to split a String into its parts along a seperator.
In your case that would be the space (" ")
Try:
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
String[] parts = fullName.split(" ");
if(parts.length() == 3){
// 3 words were entered, so there is a middle name
}
// ...
You can just add this check
if(fullName.indexOf(" ")==-1 || (fullName.indexOf(" ") == fullName.lastIndexOf(" "))){
// The first check is to check if only firstname was given and the second check is to check if only first and middle names were given.
// If first + middle is a valid scenario, you can remove the second half of the if condition
System.out.println("error, incorrect input");
System.exit(0);
}
before the below statement in your code.
int nameLength = fullName.length();
You can simply check for a == -1. indexOf returns -1 if not found (as per the docs).
if (a == -1)
System.out.println("Error, invalid input!");
else if (a == b)
...
You can narrow down to the condition you stated by following these steps:
Trim the input String fullName before statement int a = fullName.indexOf(" ");
Next check if the index of whitespace (i.e. value of a and b variables) is -1, then you can assume that the input contains only a single word, presumably Firstname
Print the error message "error, incorrect input"
since it's your first attempt, I'll give you a modified version of your code:
public class name {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
//Declares length of entire name
int nameLength = fullName.length();
//Declares int where first space is
int a = fullName.indexOf(" ");
//Declares int where second space is
int b = fullName.lastIndexOf(" ");
/*** Use the split function to split the names with spaces as delimiter **/
String[] n = fullName.split(' ');
firstName = n[0];
if( n.length == 2 ) {
lastName = n[1];
}
if( n.length > 3 ) {
lastName = n[1];
middleName = n[2];
}
String firstNameInitial = firstName.substring(0,1);
String middleNameInitial = middleName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + middleNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
//MNIC = Middle Name Initial Capitalized
String MNIC = middleNameInitial.toUpperCase();
//MNIMFC = Middle Name Initial Minus First Character
String MNIMFC = middleName.substring(1, middleName.length());
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + middleNameInitial.toUpperCase() + "." );
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + MNIC + MNIMFC);
}
}
I am setting a date_string like this:
gridcell.setTag(theday + "-" + themonth + "-" + theyear + "|" + hijri_day + "-" + hijri_month + " ("+ hijri_monthno +") " + hijri_year);
And I am splitting it like this:
String date_month_year = (String) view.getTag();
String[] dateAr = date_month_year.split("-|\\||\\(|\\)|\\s+");
This is also splitting the spaces and dash in the hijri month names i.e. Rabi al-Thani or Dhul Hijjah:
private String months[] = {"Muharram","Safar","Rabi al-Awwal","Rabi al-Thani","Jumada al-Awwal","Jumada al-Thani","Rajab","Sha\'ban","Ramadhan","Shawwal","Dhul Qa\'dah","Dhul Hijjah"};
How do I split on the date_string only and not the value of the strings in the date_string?
best way is changing the date separator - to / (slash) or .(dot) If you really wanna keep like this, than after split you can check last character on string array if it is a letter join that two string into one back..
gridcell.setTag(theday + "." + themonth + "." + theyear + "|" + hijri_day + " " + hijri_month + " ("+ hijri_monthno +") " + hijri_year);
make it like this easiest way..
I tried to split your date step by step so check if this works for you
List<String> tokens=new ArrayList<String>();
String data="theday-themonth-theyear|hijri_day-Dhul Qa\'dah (hijri_monthno) hijri_year";
String[] tmp = data.split("\\|");
//System.out.println(Arrays.toString(tmp));
for (String s:tmp[0].split("-"))
tokens.add(s);
System.out.println(tokens);// -> [theday, themonth, theyear]
String[] tmp2=tmp[1].split("\\s*\\(|\\)\\s*");
//System.out.println(Arrays.toString(tmp2));
for (String s:tmp2[0].split("-",2))
tokens.add(s);
System.out.println(tokens);// -> [theday, themonth, theyear, hijri_day, Dhul Qa'dah]
tokens.add(tmp2[1]);
tokens.add(tmp2[2]);
System.out.println(tokens);// -> [theday, themonth, theyear, hijri_day, Dhul Qa'dah, hijri_monthno, hijri_year]