0

How I can get text from a JTextArea character by character for processing each element of a string?

I tried this:

   int i, nrlitere;
   int[] valori = new int[100];
   int aux;
   int contor;
   String a = new String(new char[10000]);

   i = 1;
   contor = 0;
   nrlitere = intrare.getText().length();


   do{
       contor++;
       i++;
       a = intrare.getText();

       System.out.print(a.charAt(i));
       nrlitere--;
   }
   while(nrlitere!=0);

But it prints only the second character of a string

P.S: I also want to get spaces as characters

Thanks in advance!

Laura Chirila
  • 113
  • 1
  • 1
  • 4
  • 3
    `for (char c : intrare.getText().toCharArray()) {...}`? – MadProgrammer Feb 06 '18 at 00:00
  • I also forget to mention that all of the code above is executed when pressing a button – Laura Chirila Feb 06 '18 at 00:01
  • 3
    Stop for a second and take a step back. You problem isn't about *"how to get characters from `JTextArea`"*, but *"how to get the characters from a `String`"*, because that's what `JTextArea` will give you, a `String`. A little bit of digging through the JavaDocs would provide you wealth of information, including [`String#toCharArray`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#toCharArray--) which would provide you with an array of characters representing the `String`, which you could then loop over – MadProgrammer Feb 06 '18 at 00:03
  • Thank you very much for your advice! I am a beginner in Java programming. – Laura Chirila Feb 06 '18 at 00:06

1 Answers1

1

Simple method to get each character out of a String (which is what the text area will return)

public void test(){
    String test = "test";
    for(char c = test.toCharArray()){
    System.out.println(c);
    }
}

If you don't want to convert the string to a character array you could also do it like this:

public void test(){
    String test = "test";
    for(int i = 0; i < test.length(); i++){
    System.out.println(test.charAt(i));
   }
}
Remixt
  • 597
  • 6
  • 28