Question:
How to read a String and output the position of a character wanted by the user?
anonymous
2011-08-30 12:18:57 UTC
here's my code so far and i'm kinda stuck
//Program Finding a position of a letter
class FindPosition
{
public static void main(String args[])
{
System.out.println("Type any sentence");
String sentence = Keyboard.readString();
System.out.println("Type a character to know it's position in the sentence.");
int sentencelimit = sentence.length();
}
}
Four answers:
modulo_function
2011-08-30 13:18:34 UTC
The position of

char ch;



in

Strng str;



is given by



int pos = str.indexOf(ch):
Money_Dude
2011-08-30 19:27:44 UTC
The position is essentially the index. You need to go to the API for the String method and find the correct methods that will allow you to parse through the sentence and return the index.
?
2011-08-31 02:00:34 UTC
Use indexOf

int pos=sentence.indexOf(sentencelimit);

if(pos==-1)

//not found

it will give index in terms of string indexes which starts from 0 till string.length()-1

so you may have to add 1 while printing
anonymous
2011-08-30 19:43:20 UTC
String.IndexOf(), String.ToCharArray(), String.StartsWith(). Take your pick.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...