Can I use indexOf to pull characters from a string - java

I am trying to use index of to basically print the first letter in a string after each whitespace
I want it to grab the first letter of a persons full name entered to pring back out the intials so if they enterd Billy Bob Joe it would grab BBJ and print it like that I am trying to get it to go from each whitespace +1 to grab the chars.
I cannot use chartAt as I do not know the input the user will give.
I have this code I can get it to go to a certain white space but cannot get it to grab just the first letter after the whitespace it take the whole strign after it
String str ="Billy Joe Bob";
int targetMatch = 1;
int offset = 0;
for(int i = 0 ; i < targetMatch; i++){
int position = str.indexOf(' ',offset);
if(position != -1){
offset = position+1;
}
}
String result = str.substring(offset);
System.out.println(result);
Any help would be appreciated.

String str ="Billy Joe Bob";
int targetMatch = 1;
int offset = 0;
int position = str.indexOf(' ',offset);
String result = "";
result += str.substring(0, 1);
while(position != -1){
position++;
result += str.substring(position,position+1);
position = str.indexOf(' ', position);
}
System.out.println(result);
Try this

Ideally, you'd just split the string on whitespace using String.split. E.g.
String str = "foo bar qux";
for(String tok: str.split("\s+"))
System.out.println(tok.charAt(0));

The easiest solution I can think of is to use String.split.
String str ="Billy Joe Bob";
for (String word : str.split("\s+")) {
if (word.length >= 1) {
System.out.print(word.charAt(0));
}
}

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()));

How to count string from last 3rd comma in Java?

I am using String s="abc,def,hi,hello,lol"
By using Java, how we can split the string from the last 3rd comma and get the string and string count?
Need Output as:
,hi,hello,lol
And the count is 13.
Can you please guide me to better code?
Below is my code, but it removes String from the last 3rd comma.
String s ="abc,def,hi,hello,lol";
String[] split = s.split(",");
String newStr = "";
for(int i = 0 ; i < split.length -3 ; i++){
newStr += split[i] + ",";
}
newStr = newStr.substring(0, newStr.length() - 1);
System.out.println(newStr);
Look at String class API.
You can use lastIndexOf(String str, int fromIndex), substring(int beginIndex) and length() methods.
Follow below steps:
Call lastIndexOf 3 times and note down the return value.
Use substring to get string from this index.
Use length to get count.
Try this one,
String data ="abc,def,hi,hello,lol";
StringBuilder sb = new StringBuilder(data);
sb.reverse();
data= sb.toString();
List<String> split = new ArrayList<String>();
int startIndex = 0;
int n = 0;
for (int i = data.indexOf(',') + 1; i > 0; i = data.indexOf(',', i) + 1, n++) {
if (n % 3 == 2) {
split.add(data.substring(startIndex, i ));
startIndex = i;
}
}
split.add(data.substring(startIndex));
for(String s : split)
{
sb = new StringBuilder(s);
s = sb.reverse().toString();
System.out.println(s+" : "+s.length());
}
output :
,hi,hello,lol : 13
abc,def : 7
This one arrives at the answer in only two statements:
public static void main(String[] args) {
String s = "abc,def,hi,hello,lol";
String[] pieces = s.split("(?=,)"); // split using positive lookahead
String answer = (pieces.length < 3) ? "": // check if not enough pieces
Arrays.stream(pieces).skip(pieces.length - 3).collect(Collectors.joining());
System.out.format("Answer = \"%s\"%n", answer);
System.out.format("Count = %d%n", answer.length());
}
I split at the position before each comma using positive lookahead, because if you use a simple split(",") then your program would fail for strings that end with comma.
String output = s.substring(s.indexOf(",", 6));
System.out.println(" string from last 3rd comma -> "+ output +"\n and count -> "+ output.length() );
console output:
string from last 3rd comma -> ,hi,hello,lol and count -> 13

Word count algorithm issue

So I am trying to make a word count program where the user can paste text in to get a word count of type text in to get a word count. The typing text in works for the most part but sometimes I get a string index out of range error when I try to go back and replace text. The pasting works but I am having issues with the string index being out of range issue here as well. My logic works like this: a space equals a word, two spaces back to back is minus one word, and the end of the string counts as a word. I am relatively new to Java and I thought this was going to be an easy thing to make, I was wrong! Some help/explanation would be appreciated!
public static int getWordCount(String getInput, int e){
int numberOfWords = 0;
char l1 = 0;
char l2 = 0;
StringBuilder convertInput = new StringBuilder(getInput);
System.out.println(convertInput);
for (int i = 0, i1 = 1; i < getInput.length();i++, i1++){
l2 = convertInput.charAt(i);
if (l2 == ' '){
numberOfWords += 1;
l1 = convertInput.charAt(i1);
}
if (i == getInput.length() - 1){
numberOfWords += 1;
}
if (l2 == ' ' && l1 == ' '){
numberOfWords -= 1;
}
}
return numberOfWords;
} // end of getWordCount method
you can do this easy and quick with:
String phrase = "word1 word2 word3 word4";
String delims = " "; //u can declare more delims here like delims = " ,.{[]}\";
String[] tokens = phrase.split(delims);
tokens.length = number of words in your string

Searching for a word in a string

I want to find the positions of a particular word in an input string using java. I do not want to use regular expressions.For example if my input string is " Rama Raman Rama" and if I want to find Rama then it should give me Index number 0 and 11 as output. My code finds Rama in all the three words which I do not want. Some help?
Here is your solution :
int index=0,j=0;
String name="RAMA RAMAN RAMA";
String[] names = name.split(" ");
for(int i=0;i<names.length;i++){
if(names[i].equals("RAMA")){
if(i!=0){
while(j<i){
index += names[j++].length();
}
}
index += i;
System.out.println("Your match is at : "+index);
}
}
String name = "RAMA RAMA RAMA";
int position = name.indexOf("RAMA");
//This gives you the first position for "RAMA". If you want to have each index for each occurrence use this one:
int start = 0;
int end = 0;
while((start = name.indexOf("RAMA", end) != -1){
int position = start;
end = start;
}
You can try this
String str="Rama Raman Rama";
String[] arr=str.split(" "); // split and grab word to array
int length=0;
for(String i:arr){
if("Rama".equals(i)){
System.out.println("Index: "+length);
}
length=length+i.length()+1;// keep length count here
}
You can use the classes Pattern and Matcher. An example when you try to find the word "alpha":
String s = "alpha beta alpha anything";
Pattern p = Pattern.compile("alpha");
Matcher m = p.matcher(s);
while (m.find())
System.out.println(m.start());
It prints: 0, 11
Simply use indexOf() method. This method will let you know if word is in the text by returning index of word otherwise will return -1 means word is not found.
String str = "World is beautiful";
str.indexOf("beautiful"); // This will return value 9 as beautiful word starts at index 9
similarly
str.indexOf("beautifully"); // It will return -1 as this word doesn't exist in the text

how to get sub string after four spaces in the given string?

I have string like "align is going to school sad may me". I want to get the sub string after the four spaces. The String will be entered at run time. can anyone suggest me to find the Sub String after some set of spaces......
String st = "align is going to school sad may me";
int i = 0;
String [] strings = new String [15];
StringTokenizer stringTokenizer = new StringTokenizer (st, " ");
while (stringTokenizer.hasMoreElements ())
{
strings [i]= (String)stringTokenizer.nextElement ();
i++;
}
System.out.println ("I value is" + i);
for (int j=4; j<i; j++)
{
System.out.print (strings[j] + " ");
}
I've tried this one and it's working can you please suggest me simple method to find the Sub string after some set of spaces.
st = st.replaceAll("^(\\S*\\s){4}", "");
^ indicates that we remove only from the first character of the string.
\s is any white space. It would also remove, for example, tabulations.
\S is any non white space character.
* means any number of occurrences of the character.
So, \S* is any number of non white space characters before the white space.
{4} is obviously because you want to remove 4 white spaces.
You could also use:
st = st.replaceFirst("(\\S*\\s){4}", "");
which is the same but you don't need the ^.
In case the input string could have less than 4 white spaces:
st = st.replaceAll("^(\\S*\\s){1,4}", "");
would return you the last word of the string, only if the string doesn't end on a white space. You can be sure of that if you call trim first:
st = st.trim().replaceAll("^(\\S*\\s){1,4}", "");
What about using split?
st.split (" ", 5) [4]
It splits string by spaces, into not more than 5 chunks. Last chunk (with index 4) will contain everything after fourth space.
If it is not guaranteed that string contains 4 spaces, additional check is required:
String [] chunks = st.split (" ", 5);
String tail = chunks.length == 5 ? chunks [4] : null;
Tail will contain everything after fourth space or null, is there are less than four spaces in original string.
public static void main(String[] args) {
String st = " align is going to school sad may me ";
String trim = st.trim(); // if given string have space before and after string.
String[] splitted = trim.split("\\s+");// split the string into words.
String substring = "";
if (splitted.length >= 4) { // checks the condition
for (int i = 4; i < splitted.length; i++)
substring = substring + splitted[i] + " ";
}
System.out.println(substring);
}
This may be a overkill but it uses simple string operations (just str.indexOf(' ')).
If you needed for a school project or someting:
String str ="ada adasd dasdsa d adasdad dasasd";
int targetMatch = 4;
int offset = 0;
for(int i = 0 ; i < targetMatch; i++){
int position = str.indexOf(' ', offset);
if(position != -1){
System.out.println("position: "+ position);
offset = position+1;
}
}
String result = str.substring(offset);
System.out.println(result);
For real project... advanced regex would be better.
Here's a trivial and simple implementation that solves your problem:
String s = "I've tried this one and it's working can you please suggest";
int index = -1;
for (int i = 0; i < 4; i++) {
index = s.indexOf(' ', index + 1);
}
System.out.println(s.substring(index + 1));
It will fail if the string starts with a space or if it contains sequences of spaces. But it's a start.
Output: and it's working can you please suggest
public class MySplit {
public static void main(String agsp[]) {
String oldString = "roma h totti milan kaka juve love";
String[] allStrings = oldString.split("\\s");
String newString = "";
for (int i = 3; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
System.out.println(newString);
}
}
you can also make function like this
public String newSplit(String data, int index){
String[] allStrings = data.split("\\s");
String newString = "";
for (int i = index; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
return newString
}
The simple way using this piece of code
String thisString="Hello world go to kashmir";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
String first = parts[3];//"hello"
String second = parts[4];//"World"

Categories