String method indexOf

I have to show the number of occurances of a character in a string.
I chose the letter 'a' - here is my code, my problem is i only get one occurance, how do i show all indexes of 'a'?
thanks,
barb
// Java extension packages
import javax.swing.*;
public class IndexOf {
public static void main( String args[] )
String text ="This class is really hard \n" +
     "I'm glad I did well on the midterm \n" +
     "It took a long time.";
     String output1 =      "'This class is really hard.\n" +
               "I'm glad I did well on the midterm.\n" +
               "It took a long time.'"+ "\n\n";
     int pos;
int count = 0;
pos = text.indexOf ('a');
while ( pos != -1)
          count++;
          pos = text.indexOf ('a', pos+1);
// test indexOf to locate a character in a string
String output2 = "'a' is located at index " + text.indexOf ('a') +
text.indexOf('a');
JOptionPane.showMessageDialog( null, output1 + output2,
          "String method indexOf",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end class String IndexOf

// Try this.
String text ="This class is really hard \n" +
"I'm glad I did well on the midterm \n" +
"It took a long time.";
String result="";
for (int i=0; i<text.length(); i++)
{ if  (text.charAt(i)=='a')result += "Index: " + i + System.getProperty( "line.separator" ); }
System.out.print(result);

Similar Messages

  • How the string method indexof is really implemented

    Can please sombody please help me Iam a student of nottingham university and would like know how the java method indexof(String ) wich searches for a given substring in a string is accually implemented by those who wrote the java core classes.Well at least how the algorithm works

    Why not just take a look at the API files provided with the JDK distribution?

  • Urgent!!!   Problem on the String method and File method

    I would like to ask two questions:
    (1) From the String method, it can use .equals() method to compare two strings whether two string exactly equal or not. But what method can i use to compare two strings see whether any words exists in the string?
    (2) From the following code,
    Java.io.File outFile = new java.io.File("TestProg.java");If i would like to use a variable (e.g. let the variable be name) instead of the filename "TestProg.java", do you know how to revise the above code??
    If i write as following, is it correct???
    Java.io.File outFile = new java.io.File(""+name+"");Please help!!!

    1- To check whether a word (sunstring) exists in a longer string, you can use the following String method:
    indexOf(substring) on the string that you are searching. If the word does not exist, -1 is returned.
    2- yes you can provide a variable (of type string) in the constrcutor of File.

  • How to split a string using IndexOf?

    How would you split a string using indexOf and not using the .split method?
    Any help is appreciated :D
    Message was edited by:
    billiejoe

    would it be better to use the first or the second?
    int      indexOf(int ch)
    Returns the index within this string of the first occurrence of the specified character.
    int      indexOf(int ch, int fromIndex)
    Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
    I think the second would be helpful. so how do i read it?

  • Regex or String methods

    Hi
    Im wondering how more experienced Java developers would approach this.
    I have a parser which receives Strings according to the irc-protocol.
    servername PRIVMSG #channel :Hello worldAlmost every message is defined by the second word in the String. So its easy to just do String.split(" ") ... check the messagetype and start working with the other elements. Of course things gets a bit out of hand with compareTo(), IndexOf(), Substring() ... and all the other String methods.
    How would u use regex for this if u had to? I see this as exercise ... slower code, more work ... doesnt matter and its a plus learning more about regex.
    Example ... the line above, how would u use regex to check the messagetype "privmsg" ... channel "#channel" and the messagepart after the ':' etc ...
    many thanks in advance

    I wouldn't use regex, but split indeed, since I'd
    have very easy access to each part of the message.
    Anyway, since you want to learn regex: why don't you
    grab the Pattern API and read and try a little
    yourself? Nothing teaches you better than finding out
    yourself.Well yes regexes are nice easy and clean. And a wevy usefull if you learn them cos it gives you unlimited power of string manipulation.
    But at a high cost.
    It is verry important to make the right choice (regex or string methods) becouse it will decide how good your code looks and work.
    If the pattern that need to be parsed is simple and cam be done using string methods (including string tokenizer) regex is not the way to go.
    Normally when handling simple text patterns like above the string methods will perform about 5 times faster than regexes.
    So my recomendation is.
    If you are doing this for learning do it both ways and practice both regexes and string methods. Becouse in the industry you have know the both well.
    If you are doing this for some sort of a project and performance is a significant quality factor you need to use string methods in this perticuler situation.
    Above pattern can easilly broaken down using a combination of substring, index of and string tokenizer.

  • Which String method would be used to...

    Which string method (maybe it's not even a string method) would be used to change user input for example from:
    User input: Brandon Bell
    Changed to Bell, Brandon
    Thanks.
    Brandon Bell

    Which string method (maybe it's not even a string
    method) would be used to change user input for
    example from:
    User input: Brandon Bell
    Changed to Bell, Brandon
    Your question is very vague. What are the exact requirements? Are you assuming that the inputted string is a first name and a last name, separated by a space, and you want to change it to last name comma first name?
    If so, the methods indexOf and substring will be enough for a first, naive implementation. With that in place you might want to ask yourself:
    Will you allow the first name to have one or more spaces? Will you allow the last name to have one or more spaces? Etc, etc.

  • String method index of  urgent urgent help needed

    I am just wondering can ne one give me a working exaple of the string metyhod indexof()
    Please dont refer me to the string documentation as it makes absoloulty no sense to me at all thanks

    It returns the position of a String in another String. When you've got two Strings, a = "polly" and b = "ll",a.indexOf (b)will return 2 (the first character is index 0). If the second String is not found, the method returns -1.
    There is another variant, which takes a starting position as well. When you trya.indexOf (b, 3)you get -1, because "ll" does not appear in "ly".
    Hope this helps you on your way.
    Kind regards,
    Levi

  • How the string method index of is really implemented

    Can please sombody please help me Iam a student of nottingham university and would like know how the java method indexof(String ) wich searches for a given substring in a string is accually implemented by those who wrote the java core classes.Well at least how the algorithm works

    You could download the source and look yourself.
    In 1.3.0 it calls the indexOf(String,int) method using zero for the second argument.
    For indexOf(String,int)
    -Do some checking of the args and for zero length strings.
    -Find the first character of the passed in string
    - If found then check characters that follow (if match then return index of first)
    - If no match then find next first character and loop
    - If no first character then the match fails.

  • "Import string" method not supported in LabVIEW 7.1

    We have made an application that support multi-language (English, French, etc.). In LabVIEW 6.1, we used the "import string" VI method to support this option. The method was executed just before to open front panel. The code was based on this example found in NI Developer Zone:
    Translation/Localization Tools in LabVIEW
    (http://sine.ni.com/apps/we/niepd_web_display.disp​lay_epd4?...
    But surprise in version 7.1, this method can't be loaded without the diagram block. So the built application doesn't support it! It works only in the development interface. Why this change?
    If someone has an idea to solve this, let me know.

    If you build that example into an EXE under LabVIEW 7.1, it should work fine as long as you add the non top-level VIs as Dynamic VIs and add the language files as Support Files when you create the executable, making sure to specify in "Custom Destinations" that you want the string files to end up in the same directory as the EXE.
    Your point about the method requiring the block diagram is correct, according to the help for the method. However, I think the diagrams will be available to the run-time engine as long as you haven't purposefully removed them prior to creating the EXE in the manner described above. Maybe someone else can chime in on this point, because I know the App Builder changes a lot with every new major LabVIEW version (and sometimes, with minor versions too!).
    In any case, I just did a test where I downloaded the example you referenced, created a .BLD file as I indicated above, and got a successful executable that was able to use the Import VI Strings method to load the desired language at run-time.
    Regards,
    John

  • Import & Export Strings method

    Hi,
    I have a multilanguage application. I have used export & import
    strings methods. I have one .txt file for each language but when I
    modify something in my vi I must export all again and then modify the
    tags again for each language file... Is there a way that I can modify
    my vi and I don't have to export all again?
    Thanks,
    ToNi.

    As far as i know you need to export strings again only if you have made any changes on front panel.
    exported file is nothing but a xml file so that you can manually edit it instead of exporting everything again (helpfule if you have done very small changes on front panel)
    Tushar Jambhekar
    [email protected]
    Jambhekar Automation Solutions
    LabVIEW Consultancy, LabVIEW Training
    Rent a LabVIEW Developer, My Blog

  • NullPointerException on String methods

    All,
    I am trying to get date values on the fly and add them to my sql statement. I have a DateWorker class that provides month, day of month and year.
    When I use the class in another class, I get NullPointerException. These are just plain ol' String methods, why are they giving me problems. When I run the code on its won, it works fine.
    Code:
    package mybeans;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.util.HashMap;
    import java.util.Calendar;
    public class DateWorker {
    public DateWorker dateWorker;
         public DateWorker(){
              dateWorker = new DateWorker()
         public static void main(String[] args){
              String m = dateWorker.getMonth();
              String dm = dateWorker.getDayOfMonth();
              String dw = dateWorker.getDayOfWeek();
              String y = dateWorker.getYear();
              System.out.println("day of week " + dw + "<BR>");
              System.out.println("day of month" + dm + "<BR>");
              System.out.println("month " + m + "<BR>");
              System.out.println("year " + y + "<BR>");
         //get a Calendar instance.
         private Calendar cal = Calendar.getInstance();
         //gets the current month
         public String getMonth(){
         int x = cal.get(Calendar.MONTH) + 1;
         String s = String.valueOf(x);
         return s;
         //gets the current day of month
         public String getDayOfMonth(){
              int x = cal.get(Calendar.DAY_OF_MONTH);
              String s = String.valueOf(x);
              return s;
         //gets the current day of week
         public String getDayOfWeek(){
              int x = cal.get(Calendar.DAY_OF_WEEK) -1;
              String s = String.valueOf(x);
              return s;
         //gets the current year
         public String getYear(){
              int x = cal.get(Calendar.YEAR);
              String s = String.valueOf(x);
              return s;
    Edited by: ink86 on Oct 8, 2007 12:57 PM

    package mybeans;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.util.HashMap;
    import java.util.Calendar;
    public class DateWorker {
         public static void main(String[] args){
              DateWorker dateWorker = new DateWorker();
              String m = dateWorker.getMonth();
              String dm = dateWorker.getDayOfMonth();
              String dw = dateWorker.getDayOfWeek();
              String y = dateWorker.getYear();
              System.out.println("day of week " + dw + "<BR>");
              System.out.println("day of month" + dm + "<BR>");
              System.out.println("month " + m + "<BR>");
              System.out.println("year " + y + "<BR>");
         //get a Calendar instance.
         Calendar cal = Calendar.getInstance();
         //gets the current month
         public String getMonth(){
         int x = cal.get(Calendar.MONTH) + 1;
         String s = String.valueOf(x);
         return s;
         //gets the current day of month
         public String getDayOfMonth(){
              int x = cal.get(Calendar.DAY_OF_MONTH);
              String s = String.valueOf(x);
              return s;
         //gets the current day of week
         public String getDayOfWeek(){
              int x = cal.get(Calendar.DAY_OF_WEEK) -1;
              String s = String.valueOf(x);
              return s;
         //gets the current year
         public String getYear(){
              int x = cal.get(Calendar.YEAR);
              String s = String.valueOf(x);
              return s;
         }

  • Why is String method called not Object method

    In the below program ::
    class Test
         public void callMethod(Object o)
              System.out.println("Object Method Called");
         public void callMethod(String s)
              System.out.println("String Method Called");
         public static void main(String[] args)
              Test t = new Test();
              t.callMethod(null);
    }

    In the below program ::
    class Test
         public void callMethod(Object o)
              System.out.println("Object Method Called");
         public void callMethod(String s)
              System.out.println("String Method Called");
         public static void main(String[] args)
              Test t = new Test();
              t.callMethod(null);
    }If more than one method could be called the most specific one is called. Since a String is an Object then the String one gets called.

  • Can I use to.String() method with NamedCache

    Hi,
    I have a distributed cache. Can I use to.String() method to print the contents of cache on the console. In my case it is not working..Do I neet to import anything?
    NamedCache cache = CacheFactory.getCache("Test");
    cache.put("hello", "world");
    System.out.println(cache.toString());
    Thanks,
    Chaya

    Hi Chaya,
    Assuming that I understand your question correctly, each JVM has the same view of the cache if you're using a distributed (or optimistic, replicated, ...) cache. So when you add records from one JVM, they are visible to all the JVMs immediately (if you start up a new JVM, it will join the cluster and share the data as well).
    So if you populate a named cache from JVM1, you can simply execute the display code (from my previously reply) in any JVM connected through Coherence, and it will display the entire contents of the logical named cache.
    Jon Purdy
    Tangosol, Inc.

  • Return from String method

    Hi
    Can anyone help me:
    I have a class with a String method.
    The returned value for the method is calculated in a thread. Since I have to share the same literal for the String and run methods, the returned value for the String method is not the value that the run method is supposed to calculate for me. It just wouldn't wait until it's ready.
    What should I do? Can I block the String method to return the string until the run method is ready?

    Look up Thread.waitFor()

  • String method compareTo

    I am trying to write a program that compares two strings and comes back with the result of wether the first string is "less then", "equal to" or "more then" the second string. I have written the code and will post it. I am only coming across one error, it is saying it cannot resolve the variable "value" in....
    displayField.setText("The first string is "+ value +" the secone one!");
    here is the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CompareWindow extends JFrame{
         private JLabel string1Label,string2Label;
         private JTextField string1Field,string2Field,displayField;
         private JButton exitButton;
    public CompareWindow()
    super("String method compareTo");
    ActionEventHandler handler=new ActionEventHandler();
    Container container = getContentPane();
    container.setLayout(new FlowLayout() );
    string1Label=new JLabel("Enter first string");
    string1Field=new JTextField(20);
    string1Field.addActionListener(handler);
    container.add(string1Label);
    container.add(string1Field);
    string2Label=new JLabel("Enter second string");
    string2Field=new JTextField(20);
    string2Field.addActionListener(handler);
    container.add(string2Label);
    container.add(string2Field);
    displayField=new JTextField(30);
    displayField.setEditable(false);
    container.add(displayField);
    exitButton=new JButton("Exit");
    exitButton.addActionListener(handler);
    container.add(exitButton);
    public void displayCompare()
    displayField.setText("The first string is "+ value +" the secone one!");
    public static void main(String args[])
    CompareWindow window = new CompareWindow();
    window.setSize(400,140);
    window.setVisible(true);
    private class ActionEventHandler implements ActionListener{
    String first=string1Field.getText();
    String second=string2Field.getText();
    int compare1=0;
    String value;
    public void actionPerformed(ActionEvent event)
    String first=string1Field.getText();
    String second=string2Field.getText();
    int compare1=0;
    String value;
    if (event.getSource()==exitButton)
    System.exit(0);
    else if (event.getSource()==string1Field) {
    compare1=first.compareTo(second);
    else if (event.getSource()==string2Field) {
    compare1=first.compareTo(second);
    if (compare1<0){
    value="less then";
    else if (compare1==0){
    value="equals";
    else if (compare1>0){
    value="greater then";
    displayCompare();
    }Any help will be appreciated.

    The variable value is not accessible displayCompare method.You will need to pass it as parameter to that displayCompare method or move the declaration to the outer Class i.e. CompareWindow.

Maybe you are looking for