C/Przykłady z komentarzem: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
nawias za dużo...
Linia 322:
return 0;
}
 
</source>
===Wybieranie ciągu z łańcucha===
 
<source lang=c>
 
#include <stdio.h> // printf
/*
gcc r.c -Wall
time ./a.out
 
 
'0123456789012345678901'
'2345678'
 
/*
 
 
http://stackoverflow.com/questions/9895216/remove-character-from-string-in-c
 
"The idea is to keep a separate read and write pointers (pr for reading and pw for writing),
always advance the reading pointer, and advance the writing pointer only when it's not pointing to a given character."
 
modified
 
 
 
remove first length2rmv chars and after that take only length2stay chars from input string
output = input string
*/
void extract_str(char* str, unsigned int length2rmv, unsigned long int length2stay) {
// separate read and write pointers
char *pr = str; // read pointer
char *pw = str; // write pointer
int i =0; // index
 
while (*pr) {
if (i>length2rmv-1 && i <length2rmv+length2stay)
pw += 1; // advance the writing pointer only when
pr += 1; // always advance the reading pointer
*pw = *pr;
i +=1;
}
*pw = '\0';
}
 
int main() {
char str[] = "0123456789012345678901";
printf("'%s'\n", str);
extract_str(str, 2, 7);
printf("'%s'\n", str);
return 0;
}