Swapping the position of elements within an array in java? - java

Ok, so it's the first time I am posting out here, so bear with me.
I have a name in the format of "Smith, Bob I" and I need to switch this string around to read "Bob I. Smith". Any ideas on how to go about doing this?
This is one way that I've tried, and while it does get the job done, It looks pretty sloppy.
public static void main(String[] args) {
String s = "Smith, Bob I.", r = "";
String[] names;
for(int i =0; i < s.length(); i++){
if(s.indexOf(',') != -1){
if(s.charAt(i) != ',')
r += s.charAt(i);
}
}
names = r.split(" ");
for(int i = 0; i < names.length; i++){
}
System.out.println(names[1] +" " + names[2] + " " + names[0]);
}

If the name is always <last name>, <firstname>, try this:
String name = "Smith, Bob I.".replaceAll( "(.*),\\s+(.*)", "$2 $1" );
This will collect Smith into group 1 and Bob I. into group 2, which then are accessed as $1 and $2 in the replacement string. Due to the (.*) groups in the expression the entire string matches and will be replaced completely by the replacement, which is just the 2 groups swapped and separated by a space character.

String[] names = "Smith, Bob I.".split("[, ]+");
System.out.println(names[1] + " " + names[2] + " " + names[0]);

final String[] s = "Smith, Bob I.".split(",");
System.out.println(String.format("%s %s", s[1].trim(), s[0]));

String s = "Smith, Bob I.";
String result = s.substring(s.indexOf(" ")).trim() + " "
+ s.substring(0, s.indexOf(","));

Related

How to tokenize the string with and without delimiter in single split

Assume i have a single string content as follows
Input:
FTX+AAA+++201707141009UTC'
FTX+BBB+++201707141009UTC'
FTX+CCC+++201707141009UTC?:??'
PISCO US LTS;?:V.D??'
SOUZA?:GB?:GB'
FTX+ZZZ+++201707141009UTC'
Expected Output:
Number of segments: 4
Input:
FTX+AAA+++201707141009UTC'
FTX+CCC+++201707141009UTC?:??'
PISCO US LTS;?:V.D??'
FTX+ZZZ+++201707141009UTC'
Expected Output:
Number of segments: 3
Basically i want to consider as same line when the delimiter ' comes with a question mark. The line delimiter is '
How to tokenize and get the count the segments in Java ???
Thanks in advance.
You can use a negative lookbehind in a regex:
String input = "FTX+AAA+++201707141009UTC'\n"
+ " FTX+BBB+++201707141009UTC'\n"
+ " FTX+CCC+++201707141009UTC?:??'\n"
+ " PISCO US LTS;?:V.D??' \n"
+ " SOUZA?:GB?:GB'\n"
+ " FTX+ZZZ+++201707141009UTC'";
String[] tokens = input.split("(?<!\\?)'\\s*");
System.out.println(tokens.length);
4
But, in the second example I would expect two segments, not three...
Another alternative to the above - but again demonstrating that the second example you post may be wrong because the third line ends with a ?' which, by your definition should not be a break.
public void test() {
test("FTX+AAA+++201707141009UTC'" +
"FTX+BBB+++201707141009UTC'" +
"FTX+CCC+++201707141009UTC?:??'" +
"PISCO US LTS;?:V.D??'" +
"SOUZA?:GB?:GB'" +
"FTX+ZZZ+++201707141009UTC'");
test("FTX+AAA+++201707141009UTC'" +
"FTX+CCC+++201707141009UTC?:??'" +
"PISCO US LTS;?:V.D??'" +
"FTX+ZZZ+++201707141009UTC'");
}
private void test(String s) {
String[] split = s.split("(?<!\\?)'");
System.out.println(split.length+"->"+Arrays.toString(split));
}
prints
4->[FTX+AAA+++201707141009UTC, FTX+BBB+++201707141009UTC, FTX+CCC+++201707141009UTC?:??'PISCO US LTS;?:V.D??'SOUZA?:GB?:GB, FTX+ZZZ+++201707141009UTC]
2->[FTX+AAA+++201707141009UTC, FTX+CCC+++201707141009UTC?:??'PISCO US LTS;?:V.D??'FTX+ZZZ+++201707141009UTC]
I think what he/she want is this:
String a = "FTX+AAA+++201707141009UTC'"
+ "FTX+BBB+++201707141009UTC'"
+ "FTX+CCC+++201707141009UTC?:??'"
+ "PISCO US LTS;?:V.D??' "
+ "SOUZA?:GB?:GB'"
+ "FTX+ZZZ+++201707141009UTC'";
String result[] = a.split("'");
List<String> stringList = new ArrayList<String>(Arrays.asList(result));
for (int i = 0; i < stringList.size(); i++) {
if (!stringList.get(i).startsWith("FTX") && i != 0) {
stringList.set(i-1, stringList.get(i-1) + stringList.get(i));
stringList.remove(i);
i--;
}
}
for (int j = 0; j < stringList.size(); j++) {
System.out.println(stringList.get(j));
}
FTX+AAA+++201707141009UTC
FTX+BBB+++201707141009UTC
FTX+CCC+++201707141009UTC?:??PISCO US LTS;?:V.D?? SOUZA?:GB?:GB
FTX+ZZZ+++201707141009UTC

how to delete empty line and rest of the character in java

I want to delete empty line and rest of the character from my string, I would like to parse particular value alone from the string.
I want this value alone 23243232 from my string, after product price I've have empty line space and again I've some character so I'm using that empty line as delimiter and trying to get product price alone. But I'm getting other values also along with 23243232. Can someone help me to get only 23243232 from this string
String actualResponse = "--sGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArwzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exsGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArw\r\n"
+ "Product-Discription: form-name; productName=\"iPhone\"\r\n" + "Product-Type: Mobile\r\n"
+ "Product-Price: 23243232\r\n" + "\r\n" + "%dsafdfw32.323efaeed\r\n" + "#$#####";
String productPrice = actualResponse.substring(actualResponse.lastIndexOf("Product-Price:") + 15);
System.out.println("Printing product price ..." + productPrice);
String finalString = productPrice.replaceAll(" .*", "");
This is the output I'm getting:
Printing product price ...23243232
%dsafdfw32.323efaeed
#$#####
But I want only 23243232 - this value alone.
Apply Regular Expression for more flexibility.
String content = "--sGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArwzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exsGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArw\r\n"
+ "Product-Discription: form-name; productName=\"iPhone\"\r\n" + "Product-Type: Mobile\r\n"
+ "Product-Price: 23243232\r\n" + "\r\n" + "%dsafdfw32.323efaeed\r\n" + "#$#####";
String re1 = "\\bProduct-Price:\\s"; // Word 1
String re2 = "(\\d+)"; // Integer Number 1
Pattern p = Pattern.compile(re1 + re2, Pattern.DOTALL);
Matcher m = p.matcher(content);
while (m.find()) {
for (int i = 0; i <= m.groupCount(); i++) {
System.out.println(String.format("Group=%d | Value=%s",i, m.group(i)));
}
}
It will print out:
Group=0 | Value=Product-Price: 23243232
Group=1 | Value=23243232
first solution came in my mind. its not the best but will solve your problem.
StringBuilder finalString =new StringBuilder();
for (Character c : productPrice.toCharArray()) {
if(Character.isDigit(c)){
finalString.append(c);
}else{
break;
}
}
This is because you are printing the entire sub-string right from index: actualResponse.lastIndexOf("Product-Price:") + 15 to the end of the string.
You need to provide the end index too as a second parameter in substring method.
You need to use this:
int start = actualResponse.lastIndexOf("Product-Price:") + 15;
int end = actualResponse.indexOf("\r\n", start); // The first "\r\n" from the index `start`
String productPrice = actualResponse.substring(start, end);
This will give your final ans...
String actualResponse ="--sGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArwzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exzoF_y DmmW5DfupJDtuHlh20LL2SAbWZb8a3exsGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArw\r\n"
+ "Product-Discription: form-name; productName=\"iPhone\"\r\n" + "Product-Type: Mobile\r\n"
+ "Product-Price: 23243232\r\n" + "\r\n" + "%dsafdfw32.323efaeed\r\n" + "#$#####";
String productPrice = actualResponse.substring(actualResponse.lastIndexOf("Product-Price:") + 15);
System.out.println("Printing content lenght..." + productPrice.split("\r\n")[0]);

Name Reversing in strings

Write a method lastNameFirst that takes a string containing a name such as "Harry Smith" or "Mary Jane Lee", and that returns the string with the last name first, such as "Smith, Harry" or "Lee, Mary Jane".
im supposed to check it against
http://wiley.code-check.org/codecheck/files?repo=bjlo2&problem=05_02
i post this
String firstName = name.substring(0, name.indexOf(" "));
String lastName = name.substring(name.indexOf(" "));
String cName = lastName + ", " + firstName;
if ( lastName == " " )
{
cName = firstName;
}
return cName;
I get 0/4 everytime please help im completely lost.
It might be simpler to create an array using the split function of the String class, then join them:
String cName = String.join(", ", Collections.reverse(Arrays.asList(name.split(" "))));
String.join is only in Java 8 I believe, if you're not using 8 you can use something like the following:
String[] names = name.split(" ");
String cName = names[1] + ", " + names[0];
You should also be using the equals method for comparing String and other objects:
String[] names = name.split(" ");
String cName = names[1].equals(" ") ? names[0] : names[1] + ", " + names[0];
Please try this code
String first = name.substring(name.lastIndexOf(" "));
String last = name.substring(0, name.lastIndexOf(" "));
String result = first + "," + last;
Your solution is very close. Here's 2 hints to get to the right solution:
What separates the first and last name is the last, not the first space (consider using str.lastIndexOf(" ")).
As mentioned in the comments, when comparing strings, you can't use str1 == str2, you have to use str1.equals(str2)
You only need the last space in your name, which you can get with String.lastIndexOf(int). Then you test if that is less then 0, if so return the input name. Otherwise, concatenate and return your name in the desired format. Using a ternary (or conditional operator ? :) that might look something like,
int p = name.lastIndexOf(' ');
return (p < 0) ? name : name.substring(p + 1) + ", " + name.substring(0, p);
I put this for that Question and it passed all 4 tests they had.
public static String lastNameFirst(String name)
{
String LastToFirst = "";
if(!name.contains(" ")){
return name;
}
int index = name.indexOf(" ");
int secondIndex = name.indexOf(" ", index + 1);
// exclusive of last index
if(secondIndex != -1) {
LastToFirst += name.substring(secondIndex+1,name.length())+", ";
LastToFirst += name.substring(0,secondIndex);
}
else {
LastToFirst += name.substring(index +1,name.length()) + ", ";
LastToFirst += name.substring(0, index);
return LastToFirst;
}
A better solution for this would be to use an array, and store the characters in there and for the spacing one should add an index variable for where you want the splitting to happen- the string of interest. The solutions above do a good example of expalining this better, they consider cases where it is not a white space, but other symbols making the method more robust. Hope this helps.
I tried this code and all the four arguement works. Hope this helps!!
{
String[] names = name.split(" ");
String cName = "";
if(names.length > 2){
cName = names[2].equals(" ") ? names[0] : names[2] + ", " + names[0] + " " + names[1];
}
else if(names.length == 1){
cName = names[0]
}
else{
cName = names[1].equals(" ") ? names[0] : names[1] + ", " + names[0];
}
return cName;
}
}
public class Names
{
/**
Changes a name so that the last name comes first.
#param name a name such as "Mary Jane Lee"
#return the reversed name, such as "Lee, Mary Jane".
If name has no spaces, it is returned without change.
*/
public static String lastNameFirst(String name)
{
String result = "";
if(!name.contains(" "))
{
String firstOnly = name.substring(0);
return firstOnly;
}
else
{
String first = name.substring(name.lastIndexOf(" ")+1);
String last = name.substring(0, name.lastIndexOf(" "));
result = first + ", " + last;
return result;
}
}
}
This is the correct answer that will get you 4/4.

What's Wrong? Number Of Words In a Sentence Java

int numOfWords = str.length() - str.replace(" ", "").length();
Why does that not work? If str is equal to "Hello bye", numOfWords should equal 2, but when ran numOfWords equals 0. Any help would be greatly appreciated!
You are only replacing one blank, so the output will be 1 (at least this is what is produce in my JVM)
If you want to know the number of words then either add 1 to this number or use
str.split(" ").length;
Why dont you use :
int numOfWords = str.split(" ").length;
I hope out put is much clear
public static void main(String[] args) {
String str = "Hello bye";
System.out.println("Length of Input String = " + str.length() + " for String = " + str);
System.out.println("Length of Input String with space removed = " + str.replace(" ", "").length() + " for String = "
+ str.replace(" ", ""));
int numOfWords = str.length() - str.replace(" ", "").length();
System.out.println(numOfWords);
}
Output
Length of Input String = 9 for String = Hello bye
Length of Input String with space removed = 8 for String = Hellobye
1

How to only add something to a string if it doesn't contain it?

I am making a Lipogram program where any words with the banned letter are printed, however, the words are sometimes printed twice. How do I get it to not repeat the words?
Here is my code:
public String allWordsWith(char letter) {
String str = "";
String word = "";
s = s.replace(".", " ");
s = s.replace(",", " ");
s = s.replace("?", " ");
s = s.replace("!", " ");
s = " " + s + " ";
for (int i = 0; i <= s.lastIndexOf(letter); i++) {
if (s.charAt(i) == letter) {
if (str.contains(s.substring(s.lastIndexOf(" ", i), s.lastIndexOf(" ", i) + 1) + '\n') == true) {
} else {
word += s.substring(s.lastIndexOf(" ", i), s.indexOf(" ", i)) + '\n';
str += word;
}
}
}
return str;
}
Important clarification: Is the function run with the letter chosen as "o" on the string "hello hi hello howdy" meant to return "hello hello howdy" or "hello howdy". I.e., if the word appears twice, do you want to print it twice, or do you only want to print it once regardless of repetition?
If only once regardless of repetition, then you should be using a Set to store your data.
However, I think there's a chance you're instead dealing with an issue that when running the function with the letter chosen as "l" on that same string, "hello hi hello howdy", you are getting an output of "hello hello hello hello". Correct?
The issue here is that you are checking every letter and not testing each word. To fix this, I would use:
String[] words = s.split(" ");
to create an array of your words. Test each value in that array to see if it contains the given letter using:
if(words[index].contains(letter)){
str += " " + words[index];
}

Categories