How to iterate over a string in C?
You want:
for (i = 0; i < strlen(source); i++) {
sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:
char source[] = "This is an example.";
but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:
int len = strlen(source);
for (i = 0; i < len; i++) {
or rewrite the loop:
for (i = 0; source[i] != 0; i++) {
Iterate through every char in string stored in an array
In C, strings are really just char
arrays with a special terminator character to mark the end of the string. So, say you have something like:
char *str = "hello";
This is essentially equivalent to this:
char str[] = {'h', 'e', 'l', 'l', 'o', '\0'};
Notice that \0
character at the end of the array? This is the special terminator character that C places at the end of strings. Functions like strlen()
pretty much iterate through the char
array looking for the first occurrence of the \0
character and then stopping.
So, you can make your own version of strlen()
, say my_strlen()
like this:
int my_strlen(char *str)
{
/* Initialize len to 0 */
int len = 0;
/* Iterate through str, increment len, and stop when we reach '\0' */
while(str[len] != '\0')
len++;
/* Return the len */
return len;
}
Then within your for
loop, you can just call this function. Also, note that your calculation of the size of the numbers
array:
int length = sizeof(numbers);
will not give you the number of elements in the array. That code gives you the size (in bytes) or numbers
which is an array of char
pointers. If you want to get the number of elements, you have to divide that size by the size (in bytes) of a single element (i.e., a char
pointer). So, something like this would work:
int length = sizeof(numbers) / sizeof(numbers[0]);
Your final code can look something like this:
#include <stdio.h>
#include <math.h> // Kompilieren mit -lm : gcc -Wall -std=c11 dateiname.c -lm
int my_strlen(char *str) {
/* Initialize len to 0 */
int len = 0;
/* Iterate through str, increment len, and stop when we reach '\0' */
while(str[len] != '\0')
len++;
/* Return the len */
return len;
}
int main() {
char* numbers[] = {
"01001001",
"00101010",
"010100111001",
"011111110100101010010111",
"0001010110011010101111101111010101110110",
"01011100110000001101"};
// Add here..
// Notice the change here
int length = sizeof(numbers) / sizeof(numbers[0]);
for(int i = 0; i < length; i++ ){
int str_len = my_strlen(numbers[i]);
// Do what you need with str_len
}
return 0;
}
Iterate through an array of characters in C
the while loop can be understood as "while this string has characters" and as known in C strings or an array of chars contain a '\0' => Null character, in the end, once the while loop achieves it, it will stop the iteration.
So yeap! you are right.
How to iterate through characters in each string in a vector of strings?
Problems:
You used
||
where you should have used&&
; obviously, a character is always not equal to one of'O'
or'.'
, so the condition is always true as written; you want:if(currentgen[i][j] != 'O' && currentgen[i][j] != '.'){
^^ changedThere's also a missing semi-colon after
exit(3)
You've got warnings turned up, and it's angry you used an
int
as your iteration variable; making it asize_t
would likely fix the error (though technically, the correct change is making itvector<string>::size_type
). A better solution would be to let C++ handle iteration with a for-each loop like:for(const auto& str : currentgen){
then avoiding indexing for that loop in the first place.
Iterating through char* and comparing each char to another char
if (strcmp(string_arg, "a") == 0) {
counter++;
}
The call to strcmp
is not appropriate in your case, as it compares strings. With this statement you compare a string starting at the element pointed to by string_arg
with the string "a"
, not the character constant 'a'
. Note that "a"
is equal to 'a'
+ '\0'
.
Instead, You need to compare *string_arg
with 'a'
:
if (*string_array == 'a') {
counter++;
}
puts(string_arg);
prints a string. That is not what you want. You want to print only a single character. Use printf("%c", *string_arg);
instead to print a character.
Note that something like printf(string_arg);
is dangerous. Always use a format specifier: printf("%c", *string_arg);
. Reasony why is explained under the following link:
Why is printf with a single argument (without conversion specifiers) deprecated?
This shall be what you want:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main (int argc, char** argv) {
char* string_arg;
int counter = 0;
if (argc == 2){
for (string_arg = argv[1]; *string_arg != '\0'; string_arg++) {
printf("%c", *string_arg);
printf("\n");
if (*string_arg == 'a') {
counter++;
}
}
printf("%d times character 'a' encountered.", counter);
}
else {
printf("Error: No second argument at the program invocation!");
}
return 0;
}
For every character in string
Looping through the characters of a
std::string
, using a range-based for loop (it's from C++11, already supported in recent releases of GCC, clang, and the VC11 beta):std::string str = ???;
for(char& c : str) {
do_things_with(c);
}Looping through the characters of a
std::string
with iterators:std::string str = ???;
for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
do_things_with(*it);
}Looping through the characters of a
std::string
with an old-fashioned for-loop:std::string str = ???;
for(std::string::size_type i = 0; i < str.size(); ++i) {
do_things_with(str[i]);
}Looping through the characters of a null-terminated character array:
char* str = ???;
for(char* it = str; *it; ++it) {
do_things_with(*it);
}
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
I use a for loop to iterate the string and use charAt()
to get each character to examine it. Since the String is implemented with an array, the charAt()
method is a constant time operation.
String s = "...stuff...";
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
That's what I would do. It seems the easiest to me.
As far as correctness goes, I don't believe that exists here. It is all based on your personal style.
How can I loop through each character of a string?
sizeof(input)/sizeof(input[0])
won't work here because input
is a pointer, so sizeof(input)
will just give the size of a pointer, not the size of the array being pointed to.
Use strlen
, which calculates the numbers of characters until a null terminator:
for( i = 0; i < strlen(input) ; i++ ){
Btw you also forgot to allocate memory to input
and outputName
. To fix it:
char outputName[n];
char input[n];
where n
is some magic number denoting the number of characters you can store in the C-string including the terminating null character.
Note that this approach (using arrays instead of pointers) makes sizeof(input)/sizeof(input[0])
work as you intended.
How to loop through a string and check if it matches current character of the same string in C?
The second for loop is dead code, it is never reached as the continue
will skip to the next iteration of the for loop.
replace with a
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))
{
printf("Alphabet only please\n");
return 1;
}
I would also consider it good practice to declare c
as a char
instead of an int
, it will reduce the risks of unforeseen errors later.
char c = keycopy[i]; //current char, save and then loop
There is a more efficient way of testing if a character have been seen before without the second loop, but for this exercise I think your current code is good enough for now
Related Topics
Why Is Iostream::Eof Inside a Loop Condition (I.E. 'While (!Stream.Eof())') Considered Wrong
Is It a Good Idea to Typedef Pointers
Calling Virtual Functions Inside Constructors
How to Add Reflection to a C++ Application
How to Implement Classic Sorting Algorithms in Modern C++
Difference Between the Dot (.) Operator and -≫ in C++
Why Should I Not Include Cpp Files and Instead Use a Header
How to Execute a Functor or a Lambda in a Given Thread in Qt, Gcd-Style
Divide Array into K Contiguos Partitions Such That Sum of Maximum Partition Is Minimum
What Uses Are There For "Placement New"
When a Function Has a Specific-Size Array Parameter, Why Is It Replaced With a Pointer
Output Unicode Strings in Windows Console App
In C++, What Is a Virtual Base Class