Checking whether the String contains multiple words - java

I am getting the names as String. How can I display in the following format: If it's single word, I need to display the first character alone. If it's two words, I need to display the first two characters of the word.
John : J
Peter: P
Mathew Rails : MR
Sergy Bein : SB
I cannot use an enum as I am not sure that the list would return the same values all the time. Though they said, it's never going to change.
String name = myString.split('');
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
String finalName = topTitle + finalName;
The above code fine, but its not working. I am not getting any exception either.

There are few mistakes in your attempted code.
String#split takes a String as regex.
Return value of String#split is an array of String.
so it should be:
String[] name = myString.split(" ");
or
String[] name = myString.split("\\s+);
You also need to check for # of elements in array first like this to avoid exception:
String topTitle, subTitle;
if (name.length == 2) {
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
}
else
topTitle = name.subString(0,1);

The String.split method split a string into an array of strings, based on your regular expression.
This should work:
String[] names = myString.split("\\s+");
String topTitle = names[0].subString(0,1);
String subTitle = names[1].subString(0,1);
String finalName = topTitle + finalName;

First: "name" should be an array.
String[] names = myString.split(" ");
Second: You should use an if function and the length variable to determine the length of a variable.
String initial = "";
if(names.length > 1){
initial = names[0].subString(0,1) + names[1].subString(0,1);
}else{
initial = names[0].subString(0,1);
}
Alternatively you could use a for loop
String initial = "";
for(int i = 0; i < names.length; i++){
initial += names[i].subString(0,1);
}

You were close..
String[] name = myString.split(" ");
String finalName = name[0].charAt(0)+""+(name.length==1?"":name[1].charAt(0));
(name.length==1?"":name[1].charAt(0)) is a ternary operator which would return empty string if length of name array is 1 else it would return 1st character

This will work for you
public static void getString(String str) throws IOException {
String[] strr=str.split(" ");
StringBuilder sb=new StringBuilder();
for(int i=0;i<strr.length;i++){
sb.append(strr[i].charAt(0));
}
System.out.println(sb);
}

Related

Java PatternSyntaxException when replacing characters in a String object

I am trying to create string of this list without the following character , [] as will I want to replace all two spaces after deleting them.
I have tried the following but I am geting the error in the title.
Simple:
[06:15, 06:45, 07:16, 07:46]
Result should look as this:
06:15 06:45 07:16 07:46
Code:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll(",", " ");
String after2 = after.replaceAll(" ", " ");
String after3 = after2.replaceAll("[", "");
String after4 = after3.replaceAll("]", "");
replaceAll replaces all occurrences that match a given regular expression. Since you just want to match a simple string, you should use replace instead:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace(" ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
To answer the main question, if you use replaceAll, make sure your 1st argument is a valid regular expression. For your example, you can actually reduce it to 2 calls to replaceAll, as 2 of the substitutions are identical.
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll("[, ]", " ");
String after2 = after.replaceAll("\\[|\\]", "");
But, it looks like you're just trying to concatenate all the elements of a String list together. It's much more efficient to construct this string directly, by iterating your list and using StringBuilder:
StringBuilder builder = new StringBuilder();
for (String timeEntry: entry.getValue()) {
builder.append(timeEntry);
}
String after = builder.toString();

Spliting String into sections with keywords

I have a String i read from a .txt file with has values in sections seperated like
Text first
[section_name_1]
Text with values pattern1
...
[section_name_2]
Text with values pattern2
I need to split the sections at the section_name_# marks and add those to a String [] (Size of the array is fixed). My Code by now does not make some weird output:
//Code:
public static String[] parseFileToParams(File file)
{
String[] sections= {"[section_name_1]","[section_name_2]","[section_name_3]","[section_name_4]"};
String[] params = new String[sections.length+1];
StringBuilder sb = new StringBuilder();
String decoded = parseFile(file);// Returns the Text from the file
for(int i=0; i< sections.length;i++)
{
params[i]= decoded.split(sections[i])[1];
sb.append(params[i]);
}
return params;
}
//For Test of the output
String[] textArray = BasicOsuParser.parseFileToParams(parseFile);
for(int j = 0; j<textArray.length;j++)
{
sb.append(textArray[j]);
}
String text= sb.toString();
System.out.println (text); //Output: su f form formau fnull
// Obviously not how it should look like
Thanks for help!
Try this:
String[] sections= {"[section_name_1]","[section_name_2]","[section_name_3]","[section_name_4]"};
String textFromFile = "Text first [section_name_1] Text with values pattern1 [section_name_2] Text with values pattern2";
int count = 0;
for(int i = 0; i < sections.length; i++){
if(textFromFile.contains(sections[i])){//Use this to tell how big the parms array will be.
count++;
}
sections[i] = sections[i].replace("[", "\\[").replace("]", "\\]");//Removes the brackets from being delimiters.
}
String[] parms = new String[count+1];//Where the split items will go.
int next = 0;//The next index for the parms array.
for(String sec : sections){
String split[] = textFromFile.split(sec);//Split the file's text by the sec
if(split.length == 2){
parms[next] = split[0];//Adds split to the parms
next++;//Go to the next index for the parms.
textFromFile = split[1];//Remove text which has just been added to the parms.
}
}
parms[next] = textFromFile;//Add any text after the last split.
for(String out : parms){
System.out.println(out);//Output parms.
}
This will do what you have asked and it is commented so you can see how it works.
It's not a good idea use split() only for a one delimiter in text. This method tries to separate the text by given regexp pattern and usually used where there are more than one given delimiter in the text. Also you should screen special symbols in reqexp like '.','[' and so on. read about patterns in java. In your case better use substring() and indexOf():
public static String[] parseFileToParams(File file)
{
String[] sections= {"[section_name_1]","[section_name_2]","[section_name_3]","[section_name_4]"};
String[] params = new String[sections.length+1];
String decoded = parseFile(file);// Returns the Text from the file
int sectionStart = 0;
for (int i = 0; i < sections.length; i++) {
int sectionEnd = decoded.indexOf(sections[i], sectionStart);
params[i] = decoded.substring(sectionStart, sectionEnd);
sectionStart = sectionEnd + sections[i].length();
}
params[sections.length] = decoded.substring(sectionStart, decoded.length());
return params;
}
params[i]= decoded.split(sections[i])[1];
This returns the string after the first appearance of the sections[i] i.e. not just until the section[i+1] but till the end of file.
This loop,
for(int i=0; i< sections.length;i++)
{
params[i]= decoded.split(sections[i])[1];
sb.append(params[i]);
}
return params;
Repeatedly splits decoded into 2 halves, separated by the given section. You then append the entire 2nd half into params.
Example, pretend you wanted to split the string "abcdef" along "a", "b", etc.
You would split along a, and append "bcdef" to params, then split along b, and append "cdef" to params, etc., so you would get "bcdefcdef...f".
I think what you want to do is use real regex as the delimiter, something like params = decoded.split([section_name_.]). Look at http://www.tutorialspoint.com/java/java_string_split.htm and https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx
and if you want t

Java get the same String after split

In Java if you want to split a String by a char or a String you can do that by the split method as follow:
String[] stringWords = myString.split(" ");
But let's say i want now to create a new String using the strings in stringWords using the char * between them. Is there any solutions to do it without for/while instructions?
Here is a clear example:
String myString = "This is how the string should be";
String iWant = "This*is*how*the*string*should*be";
Somebody asks me to be more clear why i don't want just to use replace() function. I don't want to use it simply because the content of the array of strings (array stringWords in my example) changes it's content.
Here is an example:
String myString = "This is a string i wrote"
String[] stringWords = myString.split(" ");
myAlgorithmFucntion(stringWords);
Here is an example of how tha final string changes:
String iWant = "This*is*something*i*wrote*and*i*don't*want*to*do*it*anymore";
If you don't want to use replace or similar, you can use the Apache Commons StringUtils:
String iWant = StringUtils.join(stringWords, "*");
Or if you don't want to use Apache Commons, then as per comment by Rory Hunter you can implement your own as shown here.
yes there is solution to, split String with special characters like '*','.' etc. you have to use special backshlas.
String myString = "This is how the string should be";
iWant = myString.replaceAll(" ","*"); //or iWant = StringUtils.join(Collections.asList(myString.split(" ")),"*");
iWant = "This*is*how*the*string*should*be";
String [] tab = iWant.split("\\*");
Try something like this as you don't want to use replace() function
char[] ans=myString.toCharArray();
for(int i =0; i < ans.length; i++)
{
if(ans[i]==' ')ans[i]='*';
}
String answer=new String(ans);
Try looping the String array:
String[] stringWords = myString.split(" ");
String myString = "";
for (String s : stringWords){
myString = myString + "s" + "*";
}
Just add the logic to deleting the last * of the String.
Using StringBuilder option:
String[] stringWords = myString.split(" ");
StringBuilder myStringBuilder = new StringBuilder("");
for (String s : stringWords){
myStringBuilder.append(s).append("*");
}

Separate one String with ',' character into two new String

A MySQL table called item_list has a field named description, the problem is the previous programmer combined the name and description of the item in one field called description. The data is now at 20k+. Now I am going to have a problem during migration.So how do I separate one
String description="BEARING, ROLLER 23230CKE4 SPHERICAL"
into two new strings
String name="BEARING"
String description="ROLLER 23230CKE4 SPHERICAL"
Any help will be appreciated.
you can try this way
String description="BEARING, ROLLER 23230CKE4 SPHERICAL";
String [] arr=description.split(",");
System.out.println(arr[0]);
System.out.println(arr[1]);
output
BEARING
ROLLER 23230CKE4 SPHERICAL
String Split methods returns an array of strings.As in the String description has one comma(,) So the whole string will be splited into 2 strings.
You can use StringTokenizer
something like this
StringTokenizer st = new StringTokenizer(description,",");
String name=st.nextToken();
description=st.nextToken();
Unfortunately string split functions will not work correctly if there is more than 1 , in the combined string.
I recommend you split on the first , only.
int idx = description.indexOf(',');
if (idx != -1) { // if there is a comma
name = description.substring(0, idx);
description = description.substring(idx+1);
} else {
???? // no comma in description
}
combination of all the answers.., that solve the problem.
String name="",new_d ="";
String description="BEARING, ROLLER 23230CKE4 SPHERICAL";
int idx = description.indexOf(',');
if (idx != -1) { // if there is comma
String arr[]=description.split(",\\s*");
name=arr[0].toString();
new_d=arr[1].toString();
}
else {
// if there is no comma
name=description;
new_d="";
}
System.out.println(name);
System.out.println(new_d);

How to remove matched words from end of String

I want to remove the following words from end of String ‘PTE’, ‘LTD’, ‘PRIVATE’ and ‘LIMITED’
i tried the code but then i stuck. i tried this
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
String company = "Basit LTD";
for(int i=0;i<str.length;i++) {
if (company.endsWith(str[i])) {
int position = company.lastIndexOf(str[i]);
company = company.substring(0, position);
}
}
System.out.println(company.replaceAll("\\s",""));
It worked. But suppose the company is Basit LIMITED PRIVATE LTD PTE or Basit LIMITED PRIVATE PTE LTD or any combination of four words in the end. Then the above code just remove the last name i.e., PTE or PRIVATE and so on, and the output is BasitLIMITEDPRIVATELTD.
I want output to be just Basit
How can i do it?
Thanks
---------------Edit---
Please note here the company name is just an example, it is not necessary that it is always the same. may be i have name like
String company = "Masood LIMITED LTD PTE PRIVATE"
or any name that can have the above mentioned words at the end.
Thanks
You can do this in single line. no need to loop through. just use String#replaceAll(regex, str).
company = company.replaceAll("PTE$*?|LTD$*?|PRIVATE$*?|LIMITED$*?","");
If you place the unwanted words in the map it will be ommitted in the resultant string
HashMap map = new HashMap();
map.put("PTE", "");
map.put("LTD", "");
map.put("PRIVATE", "");
map.put("LIMITED", "");
String company = "Basit LTD PRIVATE PTE";
String words[] = company.split(" ");
String resultantStr = "";
for(int k = 0; k < words.length; k++){
if(map.get(words[k]) == null) {
resultantStr += words[k] + " ";
}
}
resultantStr = resultantStr.trim();
System.out.println(" Trimmed String: "+ resultantStr);
If you want to remove these suffixes only at the end of the string, then you could introduce a while loop:
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
boolean foundSuffix = true;
String company = "Basit LTD";
while (foundSuffix) {
foundSuffix = false;
for(int i=0;i<str.length;i++) {
if (company.endsWith(str[i])) {
foundSuffix = true;
int position = company.lastIndexOf(str[i]);
company = company.substring(0, position);
}
}
}
System.out.println(company.replaceAll("\\s",""));
If you don't mind transforming PTE Basit LIMITED INC to Basit (and also remove the first PTE), then replaceAll should work, as explained by others.
I was trying to do exactly same thing for one of my projects. I wrote this code few days earlier. Now I was exactly trying to find a much better way to do it, that's how I found this Question. But after seeing other answers I decided to share my version of the code.
Collection<String> stopWordSet = Arrays.asList("PTE", "LTD", "PRIVATE", "LIMITED");
String company = "Basit LTD"; //Or Anything
String[] tokens = company.split("[\#\]\\\_\^\[\"\#\ \!\&\'\`\$\%\*\+\(\)\.\/\,\-\;\~\:\}\|\{\?\>\=\<]+");
Stack<String> tokenStack = new Stack<>();
tokenStack.addAll(Arrays.asList(tokens));
while (!tokenStack.isEmpty()) {
String token = tokenStack.peek();
if (stopWordSet.contains(token))
tokenStack.pop();
else
break;
}
String formattedCompanyName = StringUtils.join(tokenStack.toArray());
Try this :
public static void main(String a[]) {
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
String company = "Basit LIMITED PRIVATE LTD PTE";
for(int i=0;i<str.length;i++) {
company = company.replaceAll(str[i], "");
}
System.out.println(company.replaceAll("\\s",""));
}
All you need is to use trim() and call your function recursively, Or each time you remove a sub string from the end, reset your i to 0.
public class StringMatchRemove {
public static void main(String[] args) {
String str="my name is noorus khan";
String search="noorus";
String newString="";
String word=str.replace(search," ");
StringTokenizer st = new StringTokenizer(word," ");
while(st.hasMoreTokens())
{
newString = newString + st.nextToken() + " ";
}
System.out.println(newString);
}
first using the replace method we get word=my name is ..... khan (Note: here(.) represents the space). Now we should have to remove these spaces for that we are creating a new string adding all the token simply.
Output: my name is khan

Categories

Resources