Get first letter of a String (more than one word) - java

I am trying to get the first letter of every word in a String:
String recInf = recursos.getString(nombre);
char[] tipoAbreviado = recInf.toCharArray();
tipoAbreviado[0] = Character.toUpperCase(tipoAbreviado[0]);
for (int i = 0; i < recInf.length() - 2; i++) {
// Es 'palabra'
if (tipoAbreviado[i] == ' ' || tipoAbreviado[i] == '.' || tipoAbreviado[i] == ',') {
// Reemplazamos
tipoAbreviado[i + 1] = Character.toUpperCase(tipoAbreviado[i + 1]);
}
nombre = tipoAbreviado.toString();
}
Finally the value of nombre is [C#3b1938ea, not the first letter of every word in recInf

You can use Arrays.toSting(your_array) to print your Array.
Take a look what toString() in Arrays do
public static String toString(long[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(a[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
But when you use tipoAbreviado.toString(); it will call toString() method in Object class.
What toString() method in Object class do?
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
That's why you are getting your current out put.

Instead of using toString on an Array which prints the memory address representation, you should create a String from char[] using new String(char[])
nombre = new String(tipoAbreviado);

You can use string's .split() with the correct regex and then just pick the first char:
String[] words = "Your String & !+ and some extraodrinary others".split("[^a-zA-Z]+");
for (String word: words ){
System.out.println(word.charAt(0));
}

You can try to fetch them with a Regular Expression.
When I use the RegEx (\w)\w+ on the string Hallo Welt, ich bin ein String, I get an array with H, W, i, b, e, S. Note: You have to run the expression as global expression (more than once).

Assuming the String object you want to process is recInf i would recommend to do it as follows:
String recInf = new String(text.replaceAll("[^\\p{L}\\p{Nd} ]+"," ")
.replaceAll("[\\s]+", " "));
String[] words = recInf.split(" ");
String[] firstLetters = new String[words.length];
for(int i=0; i<words.length;i++){
firstLetters[i]=words[i].getCharAt(0);
}

You could try this
nombre = (new StringBuilder(tipoAbreviado)).toString();

Related

I want to remove the special character and convert the next letter to uppercase "the-stealth-warrior" in Java

public class Main {
public static void main(String[] args) {
String name = "the-stealth-warrior";
for (int i = 0; i < name.length();i++){
if (name.charAt(i) == '-'){
char newName = Character.toUpperCase(name.charAt(i+1));
newName += name.charAt(i + 1);
i++;
}
}
}
}
I try to loop in every char and check if the I == '-' convert the next letter to be uppercase and append to a new String.
We can try using a split approach with the help of a stream:
String name = "the-stealth-warrior";
String parts = name.replaceAll("^.*?-", "");
String output = Arrays.stream(parts.split("-"))
.map(x -> x.substring(0, 1).toUpperCase() + x.substring(1))
.collect(Collectors.joining(""));
output = name.split("-", 2)[0] + output;
System.out.println(output); // theStealthWarrior
I think the most concise way to do this would be with regexes:
String newName = Pattern.compile("-+(.)?").matcher(name).replaceAll(mr -> mr.group(1).toUpperCase());
Note that Pattern.compile(...) can be stored rather than re-evaluating it each time.
A more verbose (but probably more efficient way) to do it would be to build the string using a StringBuilder:
StringBuilder sb = new StringBuilder(name.length());
boolean uc = false; // Flag to know whether to uppercase the char.
int len = name.codePointsCount(0, name.length());
for (int i = 0; i < name.len; ++i) {
int c = name.codePointAt(i);
if (c == '-') {
// Don't append the codepoint, but flag to uppercase the next codepoint
// that isn't a '-'.
uc = true;
} else {
if (uc) {
c = Character.toUpperCase(c);
uc = false;
}
sb.appendCodePoint(c);
}
}
String newName = sb.toString();
Note that you can't reliably uppercase single codepoints in specific locales, e.g. ß in Locale.GERMAN.

Using StringBuilder to fill in the blanks in a string

this method I tried to write is supposed to take in a string, and then an array of strings to be inserted into the original string at any "_" character, with an a/an before it, depending on what is appropriate. It will be used if the strings to be inserted are variables, and I don't know if it should be a or an. But it doesn't work. For instance, if theString is just "_" and array is {pineapple}, then it prints a pineapple_. If theString is "I am holding _, which is not a fruit, like _" and array is {pineapple, apple}, it prints I am holding _, which is not a fruit, like a pinapple_. I have looked at it, but I am unable to find the problem. I am not too sure how the stringBuilder class works, so the problem may stem from that. Thanks for any help you can give me!
public static void printWithVar(String theString, String[] array){
int arrayPosition = 0;
String insert;
StringBuilder builder = new StringBuilder(theString);
for (int i = 0;i <= theString.length();i++){
// if a "_" is found
if (theString.substring(i).equals("_")){
// if the first letter is a vowel
if (array[arrayPosition].substring(0).equalsIgnoreCase("a") || array[arrayPosition].substring(0).equalsIgnoreCase("e") || array[arrayPosition].substring(0).equalsIgnoreCase("i") || array[arrayPosition].substring(0).equalsIgnoreCase("o") || array[arrayPosition].substring(0).equalsIgnoreCase("u")){
builder.deleteCharAt(i);
insert = "an " + array[arrayPosition];
}
// if just an "a"
else{
builder.deleteCharAt(i);
insert = "a " + array[arrayPosition];
}
builder = new StringBuilder(theString = theString.substring(0, i) + insert + theString.substring(i));
arrayPosition++;
i += insert.length();
// if there are no more strings to insert
if (arrayPosition == array.length){
break;// for loop searching for "_" characters
}
}// end if an "_" is found
}// end loop
System.out.println(builder.toString());
}// end printWithVar
In response to the first comment (by 9000) I changed the code to this, and it now works.
public static void printWithVar(String theString, String[] insertArray){
String[] splitStrings = theString.split("_");
String output = "";
String insert;
// loop until there are no mmore inserts
for (int i = 0;i < insertArray.length;i++){
// if an is appropriate
if (insertArray[i].substring(i).equalsIgnoreCase("a") || insertArray[i].substring(i).equalsIgnoreCase("e") || insertArray[i].substring(i).equalsIgnoreCase("i") || insertArray[i].substring(i).equalsIgnoreCase("o") || insertArray[i].substring(i).equalsIgnoreCase("u")){
insert = "an " + insertArray[i];
}
// if a is appropriate
else{
insert = "a " + insertArray[i];
}
// add everything needed to the output string
output = output + splitStrings[i] + insert;
}// end the loop
// print the resulting string
System.out.println(output);
}// end printWithVar
If you would accept an alternative solution, I would use StringTokenizer:
public static void printWithVar(String theString, String[] array) {
final List<Character> vowels = Arrays.asList(new Character[] { 'a', 'e', 'i', 'o', 'u' });
StringTokenizer tok = new StringTokenizer(theString, "_", true);
StringBuilder result = new StringBuilder();
int i = 0;
while (tok.hasMoreTokens()) {
String token = tok.nextToken();
if (token.equals("_")) {
if (i >= array.length) {
continue;
}
String replacement = array[i];
if (vowels.contains(replacement.toLowerCase().charAt(0))) {
result.append("an " + replacement);
} else {
result.append("a " + replacement);
}
i++;
} else {
result.append(token);
}
}
System.out.println(result.toString());
}
You can use indexOf instead which returns the position of the first occurrence of "_" or -1 if it isn't found. While "_" can be found use .replace(...) method to swap out "_" with the word from the string array array[wordArrayPosition].
public static void printWithVar(String theString, String[] array){
int wordArrayPosition = 0;
String[] vowels = {"a", "e", "i", "o", "u"};
StringBuilder builder = new StringBuilder(theString);
int indexOfSymbol = builder.indexOf("_");
while (indexOfSymbol != -1) {
//Adding a or an to the word
String word = null;
if (Arrays.asList(vowels).contains(array[wordArrayPosition].charAt(0))){
word = "an " + array[wordArrayPosition];
} else {
word = "a " + array[wordArrayPosition];
}
//Checking if the word need to be capitalized
if ((indexOfSymbol == 0) || (builder.charAt(indexOfSymbol - 1) == '.')) {
word = "A" + word.substring(1);
}
builder.replace(indexOfSymbol, indexOfSymbol + 1, word);
wordArrayPosition += 1;
indexOfSymbol = builder.indexOf("_");
}
System.out.println(builder.toString());
}

How to concatenate a character to every element of an Array (Java)

I am purely novice in Java. Yesterday I was working on a home work. I had to split a string character by character and store those letters in an array. Then print this array. (DONE)
Then concatenate a single character (let's say 'a') with the every element of that array and print the results. (NOT DONE)
And at-last concatenate all those elements and create a string and print it. (NOT DONE)
String name = "Rocky";
int i;
int size = name.length();
char strings[] = new char[size];
for (i = 0; i <= size; i++) {
strings[i] = name.charAt(i);
System.out.println(strings[i]); // 1st output is done
}
The second output (concatenated char) should be:
Ra
oa
ca
ka
ya
The third output (single concatenated string) should be:
Raoacakaya
Finally I have done this and it works after-all its my homework maybe its not all up to standard. Thanks all for for replying.
String a="a";
String name="Rocky";
String temp="";
int i;
String array[]=name.split("");
String array2[]=new String[name.length()+1];
for(i=1; i<=name.length();i++)
{
System.arraycopy( array, 0, array2, 0, array.length );
System.out.println(array[i]);
}
System.out.println();
for(i=1; i<=name.length();i++)
{
System.out.println(array2[i]+a);
array2[i]=array2[i]+a;
}
for (i=1; i<array2.length;i++)
{
temp=temp+array2[i];
}
System.out.println();
System.out.println(temp);
}
}
First, you don't need to use int size, just use name.length() instead. As for the outputs, you can do it this way:
char c2 = 'a';
String all = "";
for(char c : strings)
{
String s = String.valueOf(c) + String.valueOf(c2);
System.out.println(s); // 2nd output
all += s;
}
System.out.println(all); // 3rd output
I hope I get you right. If so, this should do the trick:
public static void homeWork() {
final String name = "Rocky";
final char toAdd = 'a';
char[] array = name.toCharArray();
String concatenated = concatenate(array, toAdd);
System.out.println("Concatenated : " + concatenated);
}
public static String concatenate(char[] array, char toAdd) {
StringBuilder buidler = new StringBuilder();
for (char c : array) {
String toAppend = String.valueOf(c) + String.valueOf(toAdd);
System.out.println(toAppend);
buidler.append(toAppend);
}
return buidler.toString();
}
You run through the array with a for each loop and append
all characters with the letter you put in "toAdd".
Print the result for every loop and print the end result,
after the method returns.
Output:
Ra
oa
ca
ka
ya
Concatenated : Raoacakaya
For 2nd output:
char a = 'a';
String all = "";
for(char c : strings)
{
String s = String.valueOf(c) + String.valueOf(a);
System.out.println(s);
}
For 3rd output:
char a = 'a';
String wholeString= "";
for(char c : strings)
{
String s = String.valueOf(c) + String.valueOf(a);
System.out.print(s);
wholeString+= s;
}
System.out.println(wholeString);

Returning added string to

I'm trying to return strings in different lines given these conditions. Since I cannot use the += in Java with strings, how do I make one giant string that is spaced per line but "stacks?" In other words, how do I add a new string within a loop to an old string?
/**
Returns a String that concatenates all "offending"
words from text that contain letter; the words are
separated by '\n' characters; the returned string
does not contain duplicate words: each word occurs
only once; there are no punctuation or whitespace
characters in the returned string.
#param letter character to find in text
#return String containing all words with letter
*/
public String allWordsWith(char letter)
{
String result = "";
int i = 0;
while (i < text.length())
{
char newchar = text.charAt(i);
if (newchar == letter)
{
int index1 = text.lastIndexOf("",i);
int index2 = text.indexOf("",i);
String newstring = '\n' + text.substring(index2,index1);
}
i++;
}
return result;
}
Modify the result string, and fix your "word boundary" tests.
if (newchar == letter) {
int index1 = text.lastIndexOf(' ',i);
int index2 = text.indexOf(' ',i);
// TODO -- handle when index1 or index2 is < 0; that means it wasn't found,
// and you should use the string boundary (0 or length()) instead.
String word = text.substring( index2,index1);
result += "\n" + word;
}
If you were really concerned about performance you could use a StringBuilder and append(), but otherwise I strongly favour += for being concise & readable.
you are re-initializing your string in loop every time. Move the string declaration outsid eof loop:
Replace this
String newstring = '\n' + text.substring(index2,index1);
with
result = '\n' + text.substring(index2,index1);
First, use a StringBuilder.
Second, use System.getProperty("line.separator") to ensure proper line breaks are used.
Edited code:
public String allWordsWith(char letter)
{
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < text.length())
{
char newchar = text.charAt(i);
if (newchar == letter)
{
int index1 = text.lastIndexOf("",i);
int index2 = text.indexOf("",i);
sb.Append(text.substring(index2,index1));
sb.Append(System.getProperty("line.separator"));
//I put the new line after the word so you don't get an empty
//line on top, but you can do what you need/want to do in this case.
}
i++;
}
return result;
}
Use StringBuilder as following:
public String allWordsWith(char letter){
//String result = "";
StringBuilder result = new StringBuilder();
int i = 0;
while (i < text.length()){
char newchar = text.charAt(i);
if (newchar == letter){
int index1 = text.lastIndexOf("",i);
int index2 = text.indexOf("",i);
result.append('\n' + text.substring(index2,index1));
}
i++;
}
return result.toString();
}
String text = "I have android code with many different java, bmp and xml files everywhere in my project that I used during the drafting phase of my project.";
String letter = "a";
Set<String> duplicateWordsFilter = new HashSet<String>(Arrays.asList(text.split(" ")));
StringBuilder sb = new StringBuilder(text.length());
for (String word : duplicateWordsFilter) {
if (word.contains(letter)) {
sb.append(word);
sb.append("\n");
}
}
return sb.toString();
result is:
android
have
java,
drafting
and
many
that
phase

How to remove single character from a String by index

For accessing individual characters of a String in Java, we have String.charAt(2). Is there any inbuilt function to remove an individual character of a String in java?
Something like this:
if(String.charAt(1) == String.charAt(2){
//I want to remove the individual character at index 2.
}
You can also use the StringBuilder class which is mutable.
StringBuilder sb = new StringBuilder(inputString);
It has the method deleteCharAt(), along with many other mutator methods.
Just delete the characters that you need to delete and then get the result as follows:
String resultString = sb.toString();
This avoids creation of unnecessary string objects.
You can use Java String method called replace, which will replace all characters matching the first parameter with the second parameter:
String a = "Cool";
a = a.replace("o","");
One possibility:
String result = str.substring(0, index) + str.substring(index+1);
Note that the result is a new String (as well as two intermediate String objects), because Strings in Java are immutable.
No, because Strings in Java are immutable. You'll have to create a new string removing the character you don't want.
For replacing a single char c at index position idx in string str, do something like this, and remember that a new string will be created:
String newstr = str.substring(0, idx) + str.substring(idx + 1);
String str = "M1y java8 Progr5am";
deleteCharAt()
StringBuilder build = new StringBuilder(str);
System.out.println("Pre Builder : " + build);
build.deleteCharAt(1); // Shift the positions front.
build.deleteCharAt(8-1);
build.deleteCharAt(15-2);
System.out.println("Post Builder : " + build);
replace()
StringBuffer buffer = new StringBuffer(str);
buffer.replace(1, 2, ""); // Shift the positions front.
buffer.replace(7, 8, "");
buffer.replace(13, 14, "");
System.out.println("Buffer : "+buffer);
char[]
char[] c = str.toCharArray();
String new_Str = "";
for (int i = 0; i < c.length; i++) {
if (!(i == 1 || i == 8 || i == 15))
new_Str += c[i];
}
System.out.println("Char Array : "+new_Str);
To modify Strings, read about StringBuilder because it is mutable except for immutable String. Different operations can be found here https://docs.oracle.com/javase/tutorial/java/data/buffers.html. The code snippet below creates a StringBuilder and then append the given String and then delete the first character from the String and then convert it back from StringBuilder to a String.
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.deleteCharAt(0);
str = sb.toString();
Consider the following code:
public String removeChar(String str, Integer n) {
String front = str.substring(0, n);
String back = str.substring(n+1, str.length());
return front + back;
}
You may also use the (huge) regexp machine.
inputString = inputString.replaceFirst("(?s)(.{2}).(.*)", "$1$2");
"(?s)" - tells regexp to handle newlines like normal characters (just in case).
"(.{2})" - group $1 collecting exactly 2 characters
"." - any character at index 2 (to be squeezed out).
"(.*)" - group $2 which collects the rest of the inputString.
"$1$2" - putting group $1 and group $2 together.
If you want to remove a char from a String str at a specific int index:
public static String removeCharAt(String str, int index) {
// The part of the String before the index:
String str1 = str.substring(0,index);
// The part of the String after the index:
String str2 = str.substring(index+1,str.length());
// These two parts together gives the String without the specified index
return str1+str2;
}
By the using replace method we can change single character of string.
string= string.replace("*", "");
Use replaceFirst function of String class. There are so many variants of replace function that you can use.
If you need some logical control over character removal, use this
String string = "sdsdsd";
char[] arr = string.toCharArray();
// Run loop or whatever you need
String ss = new String(arr);
If you don't need any such control, you can use what Oscar orBhesh mentioned. They are spot on.
Easiest way to remove a char from string
String str="welcome";
str=str.replaceFirst(String.valueOf(str.charAt(2)),"");//'l' will replace with ""
System.out.println(str);//output: wecome
public class RemoveCharFromString {
public static void main(String[] args) {
String output = remove("Hello", 'l');
System.out.println(output);
}
private static String remove(String input, char c) {
if (input == null || input.length() <= 1)
return input;
char[] inputArray = input.toCharArray();
char[] outputArray = new char[inputArray.length];
int outputArrayIndex = 0;
for (int i = 0; i < inputArray.length; i++) {
char p = inputArray[i];
if (p != c) {
outputArray[outputArrayIndex] = p;
outputArrayIndex++;
}
}
return new String(outputArray, 0, outputArrayIndex);
}
}
In most use-cases using StringBuilder or substring is a good approach (as already answered). However, for performance critical code, this might be a good alternative.
/**
* Delete a single character from index position 'start' from the 'target' String.
*
* ````
* deleteAt("ABC", 0) -> "BC"
* deleteAt("ABC", 1) -> "B"
* deleteAt("ABC", 2) -> "C"
* ````
*/
public static String deleteAt(final String target, final int start) {
return deleteAt(target, start, start + 1);
}
/**
* Delete the characters from index position 'start' to 'end' from the 'target' String.
*
* ````
* deleteAt("ABC", 0, 1) -> "BC"
* deleteAt("ABC", 0, 2) -> "C"
* deleteAt("ABC", 1, 3) -> "A"
* ````
*/
public static String deleteAt(final String target, final int start, int end) {
final int targetLen = target.length();
if (start < 0) {
throw new IllegalArgumentException("start=" + start);
}
if (end > targetLen || end < start) {
throw new IllegalArgumentException("end=" + end);
}
if (start == 0) {
return end == targetLen ? "" : target.substring(end);
} else if (end == targetLen) {
return target.substring(0, start);
}
final char[] buffer = new char[targetLen - end + start];
target.getChars(0, start, buffer, 0);
target.getChars(end, targetLen, buffer, start);
return new String(buffer);
}
*You can delete string value use the StringBuilder and deletecharAt.
String s1 = "aabc";
StringBuilder sb = new StringBuilder(s1);
for(int i=0;i<sb.length();i++)
{
char temp = sb.charAt(0);
if(sb.indexOf(temp+"")!=1)
{
sb.deleteCharAt(sb.indexOf(temp+""));
}
}
To Remove a Single character from The Given String please find my method hope it will be usefull. i have used str.replaceAll to remove the string but their are many ways to remove a character from a given string but i prefer replaceall method.
Code For Remove Char:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class Removecharacter
{
public static void main(String[] args)
{
String result = removeChar("Java", 'a');
String result1 = removeChar("Edition", 'i');
System.out.println(result + " " + result1);
}
public static String removeChar(String str, char c) {
if (str == null)
{
return null;
}
else
{
return str.replaceAll(Character.toString(c), "");
}
}
}
Console image :
please find The Attached image of console,
Thanks For Asking. :)
public static String removechar(String fromString, Character character) {
int indexOf = fromString.indexOf(character);
if(indexOf==-1)
return fromString;
String front = fromString.substring(0, indexOf);
String back = fromString.substring(indexOf+1, fromString.length());
return front+back;
}
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
String line1=input.readLine();
String line2=input.readLine();
char[] a=line2.toCharArray();
char[] b=line1.toCharArray();
loop: for(int t=0;t<a.length;t++) {
char a1=a[t];
for(int t1=0;t1<b.length;t1++) {
char b1=b[t1];
if(a1==b1) {
StringBuilder sb = new StringBuilder(line1);
sb.deleteCharAt(t1);
line1=sb.toString();
b=line1.toCharArray();
list.add(a1);
continue loop;
}
}
When I have these kinds of questions I always ask: "what would the Java Gurus do?" :)
And I'd answer that, in this case, by looking at the implementation of String.trim().
Here's an extrapolation of that implementation that allows for more trim characters to be used.
However, note that original trim actually removes all chars that are <= ' ', so you may have to combine this with the original to get the desired result.
String trim(String string, String toTrim) {
// input checks removed
if (toTrim.length() == 0)
return string;
final char[] trimChars = toTrim.toCharArray();
Arrays.sort(trimChars);
int start = 0;
int end = string.length();
while (start < end &&
Arrays.binarySearch(trimChars, string.charAt(start)) >= 0)
start++;
while (start < end &&
Arrays.binarySearch(trimChars, string.charAt(end - 1)) >= 0)
end--;
return string.substring(start, end);
}
public String missingChar(String str, int n) {
String front = str.substring(0, n);
// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.
String back = str.substring(n+1, str.length());
return front + back;
}
I just implemented this utility class that removes a char or a group of chars from a String. I think it's fast because doesn't use Regexp. I hope that it helps someone!
package your.package.name;
/**
* Utility class that removes chars from a String.
*
*/
public class RemoveChars {
public static String remove(String string, String remove) {
return new String(remove(string.toCharArray(), remove.toCharArray()));
}
public static char[] remove(final char[] chars, char[] remove) {
int count = 0;
char[] buffer = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
boolean include = true;
for (int j = 0; j < remove.length; j++) {
if ((chars[i] == remove[j])) {
include = false;
break;
}
}
if (include) {
buffer[count++] = chars[i];
}
}
char[] output = new char[count];
System.arraycopy(buffer, 0, output, 0, count);
return output;
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
String remove = "AEIOU";
System.out.println();
System.out.println("Remove AEIOU: " + string);
System.out.println("Result: " + RemoveChars.remove(string, remove));
}
}
This is the output:
Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result: TH QCK BRWN FX JMPS VR TH LZY DG
For example if you want to calculate how many a's are there in the String, you can do it like this:
if (string.contains("a"))
{
numberOf_a++;
string = string.replaceFirst("a", "");
}

Categories

Resources