Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

strings

i have a String of characters.  what i want to do is output these charachters in groups of 5 i.e. qwert-yuiop. im not quite sure with how to construct the for loop
0
isarasoo
Asked:
isarasoo
1 Solution
 
CEHJCommented:
Homework?
0
 
lyonstCommented:
Store the string in an array.

The loop will read each character in the array and look something like this..

Use a for loop example if 20 characters.. this can of course be set to the number of characters in the array

for ( int counter = 1; counter <=20; Counter ++)

{

 value = array(counter);

 output += value;

if (counter % 5 == 0)

 output += "-";

}
0
 
objectsCommented:
you can get your string as an array using:

char[] array = s.toCharArray();

to access elements of the array use:

char c = array[index];

or alternately you can access characters in the string using:

char c = s.charAt(index);

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
isarasooAuthor Commented:
hi this is what ive tried  and im not having much look with it:

char[] array = b.toCharArray(); //created a char array
            for ( int l = 1; l <=b.length(); l++)


            {
               char value = array[l];
                char output += value;
               if (l % 5 == 0)              

               output += "-";


            }
please tell me what im doing wrong,  im fairly new to programming

0
 
objectsCommented:
output should be a string, and created outside your loop


String output = "";
char[] array = b.toCharArray(); //created a char array
            for ( int l = 1; l <=b.length(); l++)


            {
               char value = array[l-1];  // java array indexes start at 0
                output += value;
               if (l % 5 == 0)              

               output += "-";


            }
0
 
isarasooAuthor Commented:
oh my god ive tried everything but that

thanx
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now