Java - Get first letter of string - java

I am trying to extract the first letters of each word in a sentence the user has spoken into my app. Currently if the user speaks "Hello World 2015" it inserts that into the text field. I wish to split this so if the user speaks "Hello World 2015" only "HW2015" is inserted into the text field.
final ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
The matches variable is storing the users input in an array.I have looked into using split but not sure exactly how this works.
How would I achieve this?
Thank You

pass this regex and your list into applyRegexToList
it reads:
(get first character) or (any continuous number) or (any character after a space)
(^.{0,1})|(\\d+)|((?<=\\s)[a-zA-z])
()
public static ArrayList<String> applyRegexToList(ArrayList<String> yourList, String regex){
ArrayList<String> matches = new ArrayList<String>();
// Create a Pattern object
Pattern r = Pattern.compile(regex);
for (String sentence:yourList) {
// Now create matcher object.
Matcher m = r.matcher(sentence);
String temp = "";
//while patterns are still being found, concat
while(m.find())
{
temp += m.group(0);
}
matches.add(temp);
}
return matches;
}

You can split a string into an array of string by doing this:
String[] result = my_string.split("\\s+"); // This is a regex for matching spaces
You could then loop over your array, taking the first character of each string:
// The string we'll create
String abbrev = "";
// Loop over the results from the string splitting
for (int i = 0; i < result.length; i++){
// Grab the first character of this entry
char c = result[i].charAt(0);
// If its a number, add the whole number
if (c >= '0' && c <= '9'){
abbrev += result[i];
}
// If its not a number, just append the character
else{
abbrev += c;
}
}

Related

How to find the last word in a string

I'm trying to create a method that returns the last word in a string but I am having some trouble writing it.
I am trying to do it by finding the last blank space in the string and using a substring to find the word. This is what I have so far:
String strSpace=" ";
int Temp; //the index of the last space
for(int i=str.length()-1; i>0; i--){
if(strSpace.indexOf(str.charAt(i))>=0){
//some code in between that I not sure how to write
}
}
}
I am just beginning in Java so I don't know many of the complicated parts of the language. It would be much appreciated if someone could help me find a simple way to solve this problem. Thanks!
You can do this:
String[] words = originalStr.split(" "); // uses an array
String lastWord = words[words.length - 1];
and you've got your last word.
You are splitting the original string at every space and storing the substrings in an array using the String#split method.
Once you have the array, you are retrieving the last element by taking the value at the last array index (found by taking array length and subtracting 1, since array indices begin at 0).
String str = "Code Wines";
String lastWord = str.substring(str.lastIndexOf(" ")+1);
System.out.print(lastWord);
Output:
Wines
String#lastIndexOf and String#substring are your friends here.
chars in Java can be directly converted to ints, which we'll use to find the last space. Then we'll simply substring from there.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(phrase.lastIndexOf(' ')));
This prints the space character itself too. To get rid of that, we just increment the index at which we substring by one.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(1 + phrase.lastIndexOf(' ')));
If you don't want to use String#lastIndexOf, you can loop through the string and substring it at every space until you don't have any left.
String phrase = "The last word of this sentence is stackoverflow";
String subPhrase = phrase;
while(true) {
String temp = subPhrase.substring(1 + subPhrase.indexOf(" "));
if(temp.equals(subPhrase)) {
break;
} else {
subPhrase = temp;
}
}
System.out.println(subPhrase);
You can use: (if you are not familiar with arrays or unusual methods)
public static String lastWord(String a) // only use static if it's in the
main class
{
String lastWord = "";
// below is a new String which is the String without spaces at the ends
String x = a.trim();
for (int i=0; i< x.length(); i++)
{
if (x.charAt(i)==' ')
lastWord = x.substring(i);
}
return lastWord;
}
you just need to traverse the input string from tail when first find blank char stop traverse work and return the word.a simple code like this:
public static String lastWord(String inputs) {
boolean beforWords = false;
StringBuilder sb = new StringBuilder();
for (int i = inputs.length() - 1; i >= 0; i--) {
if (inputs.charAt(i) != ' ') {
sb.append(inputs.charAt(i));
beforWords = true;
} else if (beforWords){
break;
}
}
return sb.reverse().toString();
}
You could try:
System.out.println("Last word of the sentence is : " + string.substring (string.lastIndexOf (' '), string.length()));

Java, split string by punctuation sign, process string, add punctuation signs back to string

I have string like this:
Some text, with punctuation sign!
I am splitting it by punctuation signs, using str.split("regex"). Then I process each element (switch characters) in the received array, after splitting.
And I want to add all punctuation signs back to their places. So result should be like this:
Smoe txet, wtih pinctuatuon sgin!
What is the best approach to do that?
How about doing the whole thing in one tiny line?
str = str.replaceAll("(?<=\\b\\w)(.)(.)", "$2$1");
Some test code:
String str = "Some text, with punctuation sign!";
System.out.println(str.replaceAll("(?<=\\b\\w)(.)(.)", "$2$1"));
Output:
Smoe txet, wtih pnuctuation sgin!
Since you aren't adding or removing characters, you may as well just use String.toCharArray():
char[] cs = str.toCharArray();
for (int i = 0; i < cs.length; ) {
while (i < cs.length() && !Character.isLetter(cs[i])) ++i;
int start = i;
while (i < cs.length() && Character.isLetter(cs[i])) ++i;
process(cs, start, i);
}
String result = new String(cs);
where process(char[], int startInclusive, int endExclusive) is a method which jumbles the letters in the array between the indexes.
I'd read through the string character by character.
If the character is punctuation append it to a StringBuilder
If the character is not punctuation keep reading characters until you reach a punctuation character, then process that word and append it to the StringBuilder.
Then skip to that next punctuation character.
This prints, rather than appends to a StringBuilder, but you get the idea:
String sentence = "This is a test, message!";
for (int i = 0; i<sentence.length(); i++) {
if (Character.isLetter(sentence.charAt(i))) {
String tmp = "" +sentence.charAt(i);
while (Character.isLetter(sentence.charAt(i+1)) && i<sentence.length()) {
i++;
tmp += sentence.charAt(i);
}
System.out.print(switchChars(tmp));
} else {
System.out.print(sentence.charAt(i));
}
}
System.out.println();
You can use:
String[] parts = str.split(",");
// processing parts
String str2 = String.join(",", parts);

Replace part of the string from reference string

I have a String ArrayList consisting alphabets followed by a digit as a suffix to each of the alphabet.
ArrayList <String> baseOctave = new ArrayList();
baseOctave.add("S1");
baseOctave.add("R2");
baseOctave.add("G4");
baseOctave.add("M2");
baseOctave.add("P3");
baseOctave.add("D1");
baseOctave.add("N1");
I pass the strings from this baseOctave and few other characters as input pattern for creating an object.
MyClass obj1 = new MyClass ("S1,,R2.,M2''-");
Since I frequently make use of these kind of input patterns during object instantiation, I would like to use simple characters S, R, G, M etc.
Ex:
MyClass obj1 = new MyClass ("S,,R.,M''-");
MyClass obj2 = new MyClass ("S1,G.,M,D1");
So the alphabets used during object creation may contain digits as suffix or it may not have digit as suffix.
But inside the constructor (or in separate method), I would like to replace these simple alphabets with alphabets having suffix. The suffix is taken from the baseOctave.
Ex: above two strings in obj1 and obj2 should be "S1,,R2.,M2''-" and "S1,G4.,M2,D1"
I tied to do this, but could not continue the code below. Need some help for replacing please..
static void addSwaraSuffix(ArrayList<String> pattern) {
for (int index = 0; index < pattern.size(); index++) {
// Get the patterns one by one from the arrayList and verify and manipulate if necessary.
String str = pattern.get(index);
// First see if the second character in Array List element is digit or not.
// If digit, nothing should be done.
//If not, replace/insert the corresponding index from master list
if (Character.isDigit(str.charAt(1)) != true) {
// Replace from baseOctave.
str = str.replace(str.charAt(0), ?); // replace with appropriate alphabet having suffix from baseOctave.
// Finally put the str back to arrayList.
pattern.set(index, str);
}
}
}
Edited information is below:
Thanks for the answer. I found another solution and works fine. below is the complete code that I found working. Let me know if there is any issue.
static void addSwaraSuffix(ArrayList<String> inputPattern, ArrayList<String> baseOctave) {
String temp = "";
String str;
for (int index = 0; index < inputPattern.size(); index++) {
str = inputPattern.get(index);
// First see if the second character in Array List is digit or not.
// If digit, nothing should be done. If not, replace/insert the corresponding index from master list
// Sometimes only one swara might be there. Ex: S,R,G,M,P,D,N
if (((str.length() == 1)) || (Character.isDigit(str.charAt(1)) != true)) {
// Append with index.
// first find the corresponsing element to be replaced from baseOctave.
for (int index2 = 0; index2 < baseOctave.size(); index2++) {
if (baseOctave.get(index2).startsWith(Character.toString(str.charAt(0)))) {
temp = baseOctave.get(index2);
break;
}
}
str = str.replace(Character.toString(str.charAt(0)), temp);
}
inputPattern.set(index, str);
}
}
I assume that abbreviation is only one character and that in full pattern second character is always digit. Code below relies on this assumptions, so please inform me if they are wrong.
static String replace(String string, Collection<String> patterns) {
Map<Character, String> replacements = new HashMap<Character, String>(patterns.size());
for (String pattern : patterns) {
replacements.put(pattern.charAt(0), pattern);
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
Character c = string.charAt(i);
char next = i < string.length() - 1 ? string.charAt(i + 1) : ' ';
String replacement = replacements.get(c);
if (replacement != null && (next <= '0' || next >= '9')) {
result.append(replacement);
} else {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
ArrayList<String> baseOctave = new ArrayList<String>();
baseOctave.add("S1");
baseOctave.add("R2");
baseOctave.add("G4");
baseOctave.add("M2");
baseOctave.add("P3");
baseOctave.add("D1");
baseOctave.add("N1");
System.out.println(replace("S,,R.,M''-", baseOctave));
System.out.println(replace("S1,G.,M,D1", baseOctave));
System.out.println(replace("", baseOctave));
System.out.println(replace("S", baseOctave));
}
Results:
S1,,R2.,M2''-
S1,G4.,M2,D1
S1

replace characters according to positions in an loop

I'm busy with an hangman application, and I've come to the point where I now have to display the secret word... Now I'm thinking of creating two Strings the original that retrieves an random word from a text file and the secret word that hides... Problem is I don't know how to hide an word in '-'
So i've created the following two strings
String original = readWord();
String secret = new String(new char[original.length()]).replace('\0', '-');
Now my idea is to find the position of the char in the original string and then replace the '-' with that char in the secret String
Now the problem is when my original word is for example "elephant", so I found an loop that finds the position of the char searched
String s = "elephant";
int pos = s.indexOf('e');
while (pos > -1) {
System.out.println(pos);
pos = s.indexOf('e', pos + 1);
now this loop returns
0
2
My Question is how do I use this loop to replace the '-' in the secret string whether there is more than 1 position returned?
Because String is immutable, you could use StringBuilder to build a new string:
StringBuilder builder = new StringBuilder(secret);
for (int i = 0; i < original.length(); i++) {
if (original.charAt(i) == guessLetter) {
builder.setCharAt(i, guessLetter);
}
}
secret = builder.toString();
You would use builder.toString() as your masked word until you picked a new word. When you get a new word you would reset the masked word to '-------' etc.
you can use
String Str = new String("Welcome to Tutorialspoint.com");
// all occurrence of 'o' is replaced with 'T'
System.out.println(Str.replace('o', 'T'));

Parse String and Replace Letters Java

At input i have some string : "today snowing know " , here i have 3 words , so i must to parse them is such way : every character i must compare with all other characters , and to sum how many same characters these words have , like exemple for "o" letter will be 2 (from "today" and "snowing") or "w" letter will be 2 (from "know" and "snowing"). After that i must to replace these characters with number(transformed in char format) of letters. The result should be "13111 133211 1332".
What i did ?
First i tape some words and
public void inputStringsForThreads () {
boolean flag;
do {
// will invite to input
stringToParse = Input.value();
try {
flag = true;
// in case that found nothing , space , number and other special character , throws an exception
if (stringToParse.equals("") | stringToParse.startsWith(" ") | stringToParse.matches(".*[0-9].*") | stringToParse.matches(".*[~`!##$%^&*()-+={};:',.<>?/'_].*"))
throw new MyStringException(stringToParse);
else analizeString(stringToParse);
}
catch (MyStringException exception) {
stringToParse = null;
flag = false;
exception.AnalizeException();
}
}
while (!flag);
}
I eliminate spaces between words , and from those words make just one
static void analizeString (String someString) {
// + sign treat many spaces as one
String delimitator = " +";
// words is a String Array
words = someString.split(delimitator);
// temp is a string , will contain a single word
temp = someString.replaceAll("[^a-z^A-Z]","");
System.out.println("=============== Words are : ===============");
for (int i=0;i<words.length;i++)
System.out.println((i+1)+")"+words[i]);
}
So i try to compare for every word in part (every word is split in letters) with all letter from all words , But i don know how to count number of same letter and after replace letters with correct number of each letter??? Any ideas ?
// this will containt characters for every word in part
char[] motot = words[id].toCharArray();
// this will containt all characters from all words
char[] notot = temp.toCharArray();
for (int i =0;i<words[i].length();i++)
for (int j=0;j<temp.length ;j++)
{
if (i == j) {
System.out.println("Same word");
}
else if (motot[i] == notot[j] ) {
System.out.println("Found equal :"+lol[i]+" "+lol1[j]);
}}
For counting you might want to use a Map<Character, Integer> counter like java.util.HashMap. If getting a Value(Integer) using a specific key (Character) from counter is 'not null', then your value++ (leverage autoboxing). Otherwise put a new entry (char, 1) in the counter.
Replacing the letters with the numbers should be fairly easy then.
It is better to use Pattern Matching like this:
initially..
private Matcher matcher;
Pattern regexPattern = Pattern.compile( pattern );
matcher = regexPattern.matcher("");
for multiple patterns to match.
private final String[] patterns = new String [] {/* instantiate patterns here..*/}
private Matcher matchers[];
for ( int i = 0; i < patterns.length; i++) {
Pattern regexPattern = Pattern.compile( pattern[i] );
matchers[i] = regexPattern.matcher("");
}
and then for matching pattern.. you do this..
if(matcher.reset(charBuffer).find() ) {//matching pattern.}
for multiple matcher check.
for ( int i = 0; i < matchers.length; i++ ) if(matchers[i].reset(charBuffer).find() ) {//matching pattern.}
Don't use string matching, not efficient.
Always use CharBuffer instead of String.
Here is some C# code (which is reasonably similar to Java):
void replace(string s){
Dictionary<char, int> counts = new Dictionary<char, int>();
foreach(char c in s){
// skip spaces
if(c == ' ') continue;
// update count for char c
if(!counts.ContainsKey(c)) counts.Add(c, 1);
else counts[c]++;
}
// replace characters in s
for(int i = 0; i < s.Length; i++)
if(s[i] != ' ')
s[i] = counts[s[i]];
}
Pay attention to immutable strings in the second loop. Might want to use a StringBuilder of some sort.
Here is a solution that works for lower case strings only. Horrible horrible code, but I was trying to see how few lines I could write a solution in.
public static String letterCount(String in) {
StringBuilder out = new StringBuilder(in.length() * 2);
int[] count = new int[26];
for (int t = 1; t >= 0; t--)
for (int i = 0; i < in.length(); i++) {
if (in.charAt(i) != ' ') count[in.charAt(i) - 'a'] += t;
out.append((in.charAt(i) != ' ') ? "" + count[in.charAt(i) - 'a'] : " ");
}
return out.substring(in.length());
}

Categories