?
Solved

Indexing Char *

Posted on 2006-03-31
4
Medium Priority
?
265 Views
Last Modified: 2010-04-15
Say i've got:
char * word = "hello";

how do I index through hello.

I wanted to use a for loop going through the word one character at a time.
I thought that word[0] would give me "o" but it gives the whole thing "hello".
So i'm not sure how to index through.
0
Comment
Question by:cfans
  • 2
  • 2
4 Comments
 

Author Comment

by:cfans
ID: 16345126
The reason I'm indexing in is to then change a letter within it.
0
 
LVL 20

Accepted Solution

by:
ikework earned 800 total points
ID: 16345157
char *word = "hello";
char *pIter = word;
char letter;

while( pIter != NULL )
{
    letter = *pIter;
    printf( "%c", letter );
    ++pIter;
}

here are the items of the array
word[0] = 'h';
word[1] = 'e';
word[2] = 'l';
word[3] = 'l';
word[4] = 'o';
word[5] = '\0'; // << terminating zero-byte


hope it helps :)
ike
0
 

Author Comment

by:cfans
ID: 16345275
Ike, thanks.. I can't seem to get change an entry in it.. have any idea how to change.. like 'h' to 's'
to ultimately make the work then "sello"
0
 
LVL 20

Expert Comment

by:ikework
ID: 16345381
tdeclare your strings this way:

char word[] = "hello";

word[1] = 'x';

but this is a static-sized string, don't put more than 5 letters in it!!
otherwise use dynamically allocated arrays ...

ike
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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question