When I want to abbreviate two words I get error - java

I want to abbreviate names that given names include 3 names or more.
Also, I want to put '.' between them.
Thank you
For example
sam harris dorothy
my expectation output like below
s.h.d
My code like this
public class AbbreviateTwoWords {
public static void main(String[] args) {
String shs = abbrevName("Sam Harris");
System.out.println(shs);
}
public static String abbrevName(String name) {
String[] splitnamelist = name.split(" ");
char[] shortform = new char[10];
String point = ".";
int initial = 0;
for (String i : splitnamelist) {
if (initial % 2 == 0) {
shortform[initial] = i.charAt(0);
initial++;
} else {
shortform[initial]=point;
initial++;
}
return new String(shortform);
}
}
}

why complicate and use char array, im guessing its something with the indexes at any rate just use string and concatenate:
public static String abbrevName(String name) {
String[]splitnamelist=name.split(" ");
String shortform="";
for (String currentName:splitnamelist) {
shortform=shortform+currentName.charAt(0);
shortform=shortform+".";
}
//remove the last dot
if (shortform.length()>0)
{
shortform=shortform.substring(0, shortform.length()-1);
}
return shortform;
}

public class AbbreviateName {
public static void main(String[] args) {
AbbreviateName shs = new AbbreviateName();
shs.abbrevName("sam harris dorothy");
}
public void abbrevName(String name) {
String splitName[] = name.split(" "), seperatedName="";
int i=0; // To remove the last "+" sign.
for(String key : splitName){
seperatedName+=key;
if(i<splitName.length-1) {
seperatedName += "+";
}
i++;
}
int k;
System.out.print(seperatedName.charAt(0)+".");
//First letter always displayed
for(int j = 0,l=0; j<seperatedName.length()-1; j++){
k=j;
if(seperatedName.charAt(j)=='+'){
System.out.print(seperatedName.charAt(++k)+".");
// Letter succeeding "+" will be printed.
}
}
}
}

If you are allowed to use Java 8+ streams, you could create abbreviations like this:
import java.util.*;
import java.util.stream.*;
public class Main {
public static String abbreviate(String input) {
if (null == input || input.isEmpty()) {
// nothing to abbreviate
return input;
}
return Arrays.stream(input.split("[.\\s]+")) // split input line by 1 or more whitespaces or dot
.map(s -> s.substring(0, 1)) // get first letter
.collect(Collectors.joining(".")); // join letters into string with "." delimiter
}
}
In this code a dot "." is also included into delimiters to properly handle an abbreviation existing in the input string.
Test and online demo:
public static void main(String[] args) {
String[] inputs = {
"Jerome K. Jerome",
"Robert Louis Stevenson",
"Charles Lutwidge Dodgeson"
};
for (String s : inputs) {
System.out.printf("'%s' -> '%s'%n", s, abbreviate(s));
}
}
Output:
'Jerome K. Jerome' -> 'J.K.J'
'Robert Louis Stevenson' -> 'R.L.S'
'Charles Lutwidge Dodgeson' -> 'C.L.D'

In Java8, we can do this in a few lines.
String shs = "sam harris dorothy";
String shortform = Arrays.stream(shs.split(" "))
.map(s -> s.substring(0, 1))
.map(s -> s.concat("."))
.collect(Collectors.joining());
This is the output:
System.out.println(shortform); //Output is: s.h.d.
System.out.println(shortform.substring(0, shortform.length()-1)); //Output is: s.h.d

Related

I am writing a function in java that puts the first char in the third place and it repeats every three char as long as the word is

Following is the function that I have, it gives me desired result but I wanted to know if there is other way to approach this? May be with nested for loop?
public class RandomFunctionalities2 {
public String mixWords(String firstWord, String secondWord) {
return firstWord+secondWord;
}
public String switcheroo(String word) {
if (word.length() < 3) {
return word;
}
StringBuilder c = new StringBuilder();
int i;
for (i = 0; i < 3 * (word.length() / 3); i+=3)
c.append(word.substring(i + 1, i + 3) + word.charAt(i));
c.append(word.substring(i));
return c.toString();
}
}
TEST*
public class testingRandomFunctionalities2 {
public static void main(String[] args) {
RandomFunctionalities2 rf1 = new RandomFunctionalities2();
System.out.println(rf1.switcheroo("george"));
System.out.println(rf1.switcheroo("you"));
}
}
TEST RESULT*
eogger
ouy
Process finished with exit code 0
Another approach could be to split your input at every 3rd char and join back after swaping first and third chars of each substring:
public String switcheroo2(String word) {
String[] split = word.split("(?<=\\G...)");
StringBuilder sb = new StringBuilder();
for (String s : split){
if(s.length() > 2){
sb.append(s.substring(1)).append(s.charAt(0));
}
else {
sb.append(s);
}
}
return sb.toString();
}
You could save somemore lines using Pattern class and streams by doing something like:
public String switcheroo3(String word) {
UnaryOperator<String> op = str -> str.length() < 3 ? str : str.substring(1) + str.charAt(0);
return Pattern.compile("(?<=\\G...)")
.splitAsStream(word).map(op::apply)
.collect(Collectors.joining());
}

How I can split a word without a delimiter and perform operations over the split string in Java 8?

This is the code that I have created. I want to Split a word - "UUDDUUDD". I want to perform an operation on every character that I receive from this word. So, I tried using the below code.I'm getting the error as
error: incompatible types: String cannot be converted to String[]
If I'm not using an array i.e String[] newPath and just write as String newPath, I would not be able to perform iteration operation over the string. Can you help me to know how can I iterate over the new array?
for (String[] newPath: path.split(""))
for (char[] newPath: path.split("")
{
if (newPath[i]=="U")
{
count++;
}
else
{
count= count-1;
}
}
You have to use toCharArray() that's convert String into char[].
Remeber for char use 'U' not "U".
Here is a correct code:
public static void main(String[] args) {
String path = "UUDDUUDD";
int count = 0;
for (char newPath: path.toCharArray()) {
if (newPath == 'U') {
count++;
} else {
count--;
}
}
}
Split function returns a String array. In your for loop you should iterate over these values by using a simple String, so newPath is a String, not a String array.
If you want just count 'U' chars in String:
public static void main(String[] args) {
String path = "UUDDUUDD";
long count = path.chars()
.filter(ch -> ch == 'U')
.count();
System.out.println("number of Us: " + count);
}
Increment count if char is 'U' and decrement otherwise:
public static void main(String[] args) {
String path = "UUDDUUDD";
long countResult = path.chars()
.reduce(0, (i, j) -> j == 'U' ? i + 1 : i - 1);
System.out.println(countResult);
}
The return type of String.split() is String[].
So if we are iterating over the result of String.split() we use a String:
class Test {
public static void main(String[] args) {
for (String c : "ABCD".split("")) {
System.out.println(c);
}
}
}

How to write static recursive method in Java?

I want to write codes using a static recursive method in Java, cleanString(String s) that accepts a string of letters s and returns a string where adjacent letters that are the same are replaced by a single occurrence of that letter. The method is case-sensitive.
For example:
cleanString("sensssaatiionnaallll!") -> "sensational!"
cleanString("PPProoggggraamm") -> "Program"
cleanString("Lletterriiing") -> "Lletering"
Try this:
public class Main {
public static void main(String[] args) {
System.out.println(cleanString("sensssaatiionnaallll!"));
}
static String cleanString(String input)
{
if(input.length()<1) //To stop infinite recursion
return input;
var first = input.charAt(0);
var count = input.chars().takeWhile(x -> x == first).count();
return first + cleanString(input.substring((int)count));
}
}
First, it checks if the length of the string is less than 1. If it is, return the string itself (which is empty) and stop the recursion.
Next get the first character of the string. (e.g PPProoggggraamm -> P)
Get the number of characters in the start that equal the first character (3 in the case of PPProoggggraamm)
Call the function again, but this time lopping off the first n characters from the above step, and prepending the first character. ('P' + cleanString("rooggggraamm"))
Shortest recursive code to remove adjacent characters from the input string.
public class StackOverflow {
static String cleanString(String input) {
return input==null || input.length()<=1?input:cleanStringWrapper(input.substring(1),input.substring(0,1));
}
static String cleanStringWrapper(String input, String result) {
if (input.length() - 1 <= 0) {
return result+(result.charAt(result.length() - 1)!=input.charAt(0)?input:"");
} else {
return cleanStringWrapper(input.substring(1), result+(result.charAt(result.length() - 1) != input.charAt(0)?input.charAt(0):""));
}
}
public static void main(String[] args)
{
System.out.println(cleanString("OOPS"));
}
}
Output:
cleanString("sensssaatiionnaallll!") -> "sensational!"
cleanString("PPProoggggraamm") -> "Program"
cleanString("Lletterriiing") -> "Lletering"
cleanString("Gooooogle") -> "Gogle"
cleanString("ABC") -> "ABC"
cleanString("A") -> "A"
cleanString("") -> ""
cleanString(null) -> null
It just generate a new String and exclude the repeat characters.
static String cleanString(String input) {
if(input == null) return null;
char lastChar = 0;
StringBuilder output = new StringBuilder(input.length());
for (int i=0,n=input.length(); i<n; i++) {
char c = input.charAt(i);
if(c != lastChar) {
lastChar = c;
output.append(c);
}
}
return output.toString();
}
Recursive method:
public class Example {
public static int main(String[] args) {
String input = "sensssaatiionnaallll";
String output = cleanString(input, 0);
System.out.println(output); // print: sensational
return 0;
}
private static String cleanString(String input, int index) {
if(input == null) return "";
if(index >= input.length()) return "";
StringBuilder output = new StringBuilder();
char current = input.charAt(index);
int nextIndex = index + 1;
if(nextIndex >= input.length()) {
return output.append(current).toString();
}
char next = input.charAt(nextIndex);
if (current != next) {
output.append(current);
}
output.append(cleanString(input, nextIndex));
return output.toString();
}
}
Why you want to make static method for that?
Whay i understood is that you want to remove repeated characters from your input string.
You can do it below code as well.
StringBuilder sb = new StringBuilder();
str.chars().distinct().forEach(c -> sb.append((char) c));
If you want you can make a method of this 2 lines as a feature in your code.
Hope this helps!

Get value from 2nd slash

Below is my string
/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk
I want to get the value after 2nd slash(/) which is
D:/coinFiles/Coin-v1.1.8.apk
How should I do this?
Note :
I am getting this string in my rest call in variable restOfTheUrl
#RequestMapping(value="/downloadAPK/**", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response, HttpServletRequest request) throws IOException {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
}
I want to get the complete file location
Even a better and simple solution \\/.*?\\/(.*)
Regex Demo
\\/.*?\\/(.*) : \\/.*?\\/ match the first two / and content between
(.*) : capture whatever is after first two /
String s = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
String result=s.replaceAll("\\/.*?\\/(.*)", "$1");
System.out.println(result);
Output :
D:/coinFiles/Coin-v1.1.8.apk
You can use a regex with replceAll if there is always one : in the input
String s = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
String result=s.replaceAll(".*([A-Za-z]:.*)", "$1");
System.out.println(result);
Output :
D:/coinFiles/Coin-v1.1.8.apk
.*([A-Za-z]:.*) : .* matches any character
([A-Za-z]:.*) : [A-Za-z] match a character like D
() : is a capturing group which is represented as $1
:.* : will capture all after :
Otherwise
String s = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
// find first index of /
int index =s.indexOf("/");
// find second index of /
index=s.indexOf("/", index+1);
// fetch substring from second index+1 of /
System.out.println(s.substring(index+1));
Output :
D:/coinFiles/Coin-v1.1.8.apk
If you are sure, always colon(:) will exist in string, then you can use this.
import java.io.*;
public class Test {
public static void main(String args[]) {
String str = new String("/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk");
String subStr1 = new String(":");
System.out.println("value "+ str.substring(str.indexOf( subStr1 )-1));
}
}
output:
value D:/coinFiles/Coin-v1.1.8.apk
This code for without colon (:)
public class HelloWorld{
public static void main(String args[]) {
String str = new String("/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk");
System.out.println("before value" + str);
str = getPattern(str, 2);
System.out.println("\nAfter value "+ str);
}
public static String getPattern(String str, Integer pos) {
for(int i = 0; i< pos; i ++) {
str = str.substring(str.indexOf("/") +1);
}
return str;
}
}
Output
before value/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk
After value D:/coinFiles/Coin-v1.1.8.apk
You can iteratively find the index. You could also write a recursive version, but this does not perform the substring until the final step; which means it will not pollute the String pool.
public class StringUtil {
public static void main(String[] args) {
String path = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
System.out.println(substring2(path, "/", 2)); // D:/coinFiles/Coin-v1.1.8.apk
String test = "this---is---a---test";
System.out.println(substring2(test, "---", 3)); // test
}
public static String substring2(String src, String str, int offset) {
if (offset <= 0) {
return src;
}
int index = -1, pos = 0;
while (pos++ < offset) {
index = src.indexOf(str, index + 1);
}
return src.substring(index + str.length(), src.length());
}
}
Here is a StringTokenizer version which handles indexing for you.
import java.util.Enumeration;
import java.util.StringTokenizer;
public class StringUtil {
public static void main(String[] args) {
String path = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
System.out.println(substring2(path, "/", 1)); // D:/coinFiles/Coin-v1.1.8.apk
String test = "this---is---a---test";
System.out.println(substring2(test, "---", 3)); // test
}
public static String substring2(String src, String delim, int offset) {
StringTokenizer tokenizer = new StringTokenizer(src, delim);
while (offset-- > 0 && tokenizer.hasMoreTokens()) {
tokenizer.nextToken();
}
return join(tokenizer, delim);
}
public static <T> String join(Enumeration<T> enumeration, String delim) {
StringBuffer buff = new StringBuffer();
while (enumeration.hasMoreElements()) {
buff.append(enumeration.nextElement());
if (enumeration.hasMoreElements()) {
buff.append(delim);
}
}
return buff.toString();
}
}

How can return part of a string between two comma characters?

say I'm given a set of strings that looks like this:
0,test0,dummy
1,test,dummy
2,test1,dummy
3,test2,dummy
4,test3,dum,dum,dummy
I wrote code that can return only what's before the last ",":
public class RandomTest {
public static void main(String[] args) {
String testFile = "synsets11.txt";
In testIn = new In(testFile);
while (testIn.hasNextLine()) {
String line = testIn.readLine();
String result = line.substring(0, line.lastIndexOf(","));
List<String> synList = Arrays.asList(result.split(","));
for (String i : synList) {
System.out.println(i);
}
}
}
}
What I intended to do was only return the part of the string that was between the first and second "," characters, so my code above doesn't work for the last line of text. How do I only return what's between the first and second comma?
In this case, only test0, test, test1, test2, and test3.
thanks!
use split() method like this :
public static void main(String[] args) {
String s = "0,prop,dummy";
System.out.println(s.split(",")[1]);
}
O/P:
prop
NOTE : You have to check whether the String contains atleast 1 , (unless you want an ArrayIndexOutOfBoundsException :P)
Rather than using lastIndexOf, use indexOf twice:
int pos = line.indexOf(',', line.indexOf(',')+1);
String result = line.substring(0, pos);
You could use string.replaceAll function.
string.replaceAll("(?m)^[^,]*,|,.*", "");
DEMO
String s = "0,test0,dummy\n" +
"1,test,dummy\n" +
"2,test1,dummy\n" +
"3,test2,dummy\n" +
"4,test3,dum,dum,dummy";
System.out.println(s.replaceAll("(?m)^[^,]*,|,.*", ""));
What about StringTokenizer?
public class RandomTest {
public static void main(String[] args) {
String testFile = "synsets11.txt";
In testIn = new In(testFile);
StringTokenizer stok = null;
while (testIn.hasNextLine()) {
String line = testIn.readLine();
stok = new StringTokenizer(line,",");
for(int i = 0; i< stok.countTokens() ; i++){
String str = st.nextToken();
if( i == 1){
System.out.println(str);
}else if( i > 1){break;}
}// for
}// while
}//main
}//class

Categories