C/String/String General — различия между версиями
Admin (обсуждение | вклад) м (1 версия: Импорт контента...) |
|
(нет различий)
|
Версия 17:20, 25 мая 2010
Содержание
- 1 A function to read a string terminated by an arbitrary character
- 2 Analyze comma-separated list of words
- 3 Arrays of Pointers to Strings
- 4 Function: Sort string
- 5 How to copy a string
- 6 Looking for palindromes
- 7 Managing memory and storing strings
- 8 Output a name and address
- 9 Output a name and address 2
- 10 Output a name and address in a single statement
- 11 Output string
- 12 Reading a string with gets()
- 13 Removing spaces and puctuation from a string
- 14 REVERSI An Othello type game
- 15 Storing and displaying proverbs in order of length
- 16 String length and string compare
- 17 Use gets to get the whole string
A function to read a string terminated by an arbitrary character
<source lang="cpp">
- include <stdio.h>
- include <string.h>
- define MAX_SIZE 100
char* getString(char *buffer, char end_char); int main() {
char buffer[MAX_SIZE]; int i = 0; printf("Enter a string terminated by a semi-colon:\n"); getString(buffer, ";"); printf(":\n%s\n", buffer);
} char* getString(char *buffer, char end_char) {
size_t i = 0; /* Read a character until end_char is entered */ while((buffer[i++] = getchar()) != end_char) ; buffer[i-1] = "\0"; /* Overwrite end_char with string terminator */ return buffer;
}
</source>
Analyze comma-separated list of words
<source lang="cpp">
- include <stdio.h>
- include <string.h>
int main() {
char list[5000]="This, is, a, test."; char words[500][20]; const char comma = ","; const char space = " "; int count = 0; int word_length = 0; int i = 0; while(list[i] != "\0") { /* Skip over spaces and commas */ while(list[i] == space || list[i] == comma) ++i; /* Copy characters that are not space, comma or \0 as part of a word */ while(list[i] != space && list[i] != comma && list[i] != "\0") words[count][word_length++] = list[i++]; words[count++][word_length] = "\0"; /* Append terminator */ word_length = 0; } printf("\nThe words in the list are:\n"); for(i = 0 ; i<count ; i++) printf("%s\n",words[i]);
}
</source>
Arrays of Pointers to Strings
<source lang="cpp">
- include <stdio.h>
- define BUFFER_LEN 500
int main() {
char buffer[BUFFER_LEN]; char *pS[3] = { NULL }; char *pbuffer = buffer; int i = 0; for (i=0; i<3 ; i++) { printf("\nEnter a message\n"); *(pS + i) = pbuffer; /* Get input till Enter pressed */ while ((*pbuffer++ = getchar()) != "\n"); *(pbuffer - 1) = "\0"; } printf("\nThe strings you entered are:\n\n"); for(i = 0 ; i<3 ; i++) printf("%s\n", *(pS+i)); printf("The buffer has %d characters unused.\n",&buffer[BUFFER_LEN - 1] - pbuffer + 1);
}
</source>
Function: Sort string
<source lang="cpp">
- include <stdio.h>
- include <stdlib.h>
- include <string.h>
- define TRUE 1
- define FALSE 0
void str_sort(char *[], int); void str_out(char *[], int);
- define BUFFER_LEN 240
- define NUM_P 50
int main() {
char *pS[NUM_P]; int count = 3; int i = 0; /* Loop counter */ pS[0] = "A"; pS[1] = "C"; pS[2] = "B"; str_sort( pS, count ); printf("\nYour input sorted in order is:\n\n"); for (i = 0 ; i<count ; i++) { printf("%s\n", pS[i]); /* Display a string */ free(pS[i]); /* Free memory for the string */ pS[i] = NULL; }
} void str_sort(char *p[], int n) {
char *pTemp = NULL; int i = 0; int sorted = FALSE; while(!sorted) { sorted = TRUE; for( i = 0 ; i<n-1 ; i++ ) if(strcmp(p[i], p[i + 1]) > 0) { sorted = FALSE; pTemp= p[i]; p[i] = p[i + 1]; p[i + 1] = pTemp; } }
}
</source>
How to copy a string
<source lang="cpp">
- include <string.h>
- include <stdio.h>
int main(void) {
char str[5]; strcpy(str, "this is a test"); printf(str); return 0;
}
</source>
Looking for palindromes
<source lang="cpp">
- include <stdio.h>
- include <string.h>
- include <ctype.h>
int main() {
char sentence_chars[500] ="level"; int i = 0; int j = 0; int length = 0; length = strlen(sentence_chars); for(i = 0 ; i<length/2 ; i++){ if(sentence_chars[i] != sentence_chars[length-1-i]) { printf("\n The sentence you entered is not a palindrome.\n"); break; } }
}
</source>
Managing memory and storing strings
<source lang="cpp">
- include <stdio.h>
- define BUFFER_LEN 500
int main() {
char buffer[BUFFER_LEN]; /* Store for strings */ char *pS1 = NULL; /* Pointer to first string */ char *pS2 = NULL; /* Pointer to second string */ char *pS3 = NULL; /* Pointer to third string */ char *pbuffer = buffer; /* Pointer to buffer */ printf("\nEnter a message\n"); pS1 = pbuffer; while ((*pbuffer++ = getchar()) != "\n"); *(pbuffer - 1) = "\0"; printf("\nEnter another message\n"); pS2 = pbuffer; while ((*pbuffer++ = getchar()) != "\n"); *(pbuffer - 1) = "\0"; printf("\nEnter another message\n"); pS3 = pbuffer; while((*pbuffer++ = getchar()) != "\n"); *(pbuffer - 1) = "\0"; printf("\nThe strings you entered are:\n\n%s\n%s\n%s",pS1, pS2, pS3); printf("\nThe buffer has %d characters unused.\n",&buffer[BUFFER_LEN - 1] - pbuffer + 1);
}
</source>
Output a name and address
<source lang="cpp">
- include <stdio.h>
void main() {
/* The double quotes must appear as the escape sequence \" */ printf("\n\"It"s freezing in here,\" he said coldly.\n");
}
</source>
Output a name and address 2
<source lang="cpp">
- include <stdio.h>
void main() {
printf("\nGeorge Washington"); printf("\n3200 George Washington Memorial Parkway"); printf("\nMount Vernon"); printf("\nVirginia 22121\n");
}
</source>
Output a name and address in a single statement
<source lang="cpp">
- include <stdio.h>
void main() {
/* The compiler will automatically join strings together into a single string when they immediately follow one another */ printf("\nGeorge Washington" "\n3200 George Washington Memorial Parkway" "\nMount Vernon\nVirginia 22121\n");
}
</source>
Output string
<source lang="cpp">
- include <stdio.h>
int main(void) {
printf("%s %s %s", "1", "2", "3"); return 0;
}
</source>
Reading a string with gets()
<source lang="cpp">
- include <stdio.h>
void main() {
char initial[2] = { 0 }; char name[80] = { 0 }; printf("Your first initial: "); gets(initial); printf("Your name: " ); gets(name); if(initial[0] != name[0]) printf("\n%s,you got your initial wrong.\n", name); else printf("\nHi, %s. Your initial is correct. Well done!\n", name);
}
</source>
Removing spaces and puctuation from a string
<source lang="cpp">
- include <stdio.h>
- include <ctype.h>
int main() {
char buffer[80] = "This is a test"; char *pbuffer1 = buffer; char *pbuffer2 = buffer; pbuffer1 = buffer; /* Reset pointer to start */ while(*pbuffer1 != "\0") { if(ispunct(*pbuffer1) || isspace(*pbuffer1)) { ++pbuffer1; continue; } else *pbuffer2++ = *pbuffer1++; /* otherwise, copy the character */ } *pbuffer2 = "\0"; /* Append string terminator */ printf("\n%s\n", buffer);
}
</source>
REVERSI An Othello type game
<source lang="cpp"> /* Beginning C, Third Edition
By Ivor Horton ISBN: 1-59059-253-0 Published: Apr 2004 Publisher: apress
- /
- include <stdio.h>
- include <ctype.h>
- define SIZE 6 /* Board size - must be even */
/* Function prototypes */ void display(char board[][SIZE]); int valid_moves(char board[][SIZE], int moves[][SIZE], char player); void make_move(char board[][SIZE], int row, int col, char player); void computer_move(char board[][SIZE], int moves[][SIZE], char player); int best_move(char board[][SIZE], int moves[][SIZE], char player); int get_score(char board[][SIZE], char player); void main() {
char board [SIZE][SIZE] = { 0 }; /* The board */ int moves[SIZE][SIZE] = { 0 }; /* Valid moves */ int row = 0; /* Board row index */ int col = 0; /* Board column index */ int no_of_games = 0; /* Number of games */ int no_of_moves = 0; /* Count of moves */ int invalid_moves = 0; /* Invalid move count */ int comp_score = 0; /* Computer score */ int user_score = 0; /* Player score */ char y = 0; /* Column letter */ int x = 0; /* Row number */ char again = 0; /* Replay choice input */ int player = 0; /* Player indicator */ printf("\nREVERSI\n\n"); printf("You can go first on the first game, then we will take turns.\n"); printf(" You will be white - (O)\n I will be black - (@).\n"); printf("Select a square for your move by typing a digit for the row\n " "and a letter for the column with no spaces between.\n"); printf("\nGood luck! Press Enter to start.\n"); scanf("%c", &again); /* Prompt for how to play - as before */ /* The main game loop */ do { /* On even games the player starts; */ /* on odd games the computer starts */ player = ++no_of_games % 2; no_of_moves = 4; /* Starts with four counters */ /* Blank all the board squares */ for(row = 0; row < SIZE; row++) for(col = 0; col < SIZE; col++) board[row][col] = " "; /* Place the initial four counters in the center */ board[SIZE/2 - 1][SIZE/2 - 1] = board[SIZE/2][SIZE/2] = "O"; board[SIZE/2 - 1][SIZE/2] = board[SIZE/2][SIZE/2 - 1] = "@"; /* The game play loop */ do { display(board); /* Display the board */ if(player++ % 2) { /* It is the player"s turn */ if(valid_moves(board, moves, "O")) { /* Read player moves until a valid move is entered */ for(;;) { fflush(stdin); /* Flush the keyboard buffer */ printf("Please enter your move (row column): "); scanf("%d%c", &x, &y); /* Read input */ y = tolower(y) - "a"; /* Convert to column index */ x--; /* Convert to row index */ if( x>=0 && y>=0 && x<SIZE && y<SIZE && moves[x][y]) { make_move(board, x, y, "O"); no_of_moves++; /* Increment move count */ break; } else printf("Not a valid move, try again.\n"); } } else /* No valid moves */ if(++invalid_moves<2) { fflush(stdin); printf("\nYou have to pass, press return"); scanf("%c", &again); } else printf("\nNeither of us can go, so the game is over.\n"); } else { /* It is the computer"s turn */ if(valid_moves(board, moves, "@")) /* Check for valid moves */ { invalid_moves = 0; /* Reset invalid count */ computer_move(board, moves, "@"); no_of_moves++; /* Increment move count */ } else { if(++invalid_moves<2) printf("\nI have to pass, your go\n"); /* No valid move */ else printf("\nNeither of us can go, so the game is over.\n"); } } }while(no_of_moves < SIZE*SIZE && invalid_moves<2); /* Game is over */ display(board); /* Show final board */ /* Get final scores and display them */ comp_score = user_score = 0; for(row = 0; row < SIZE; row++) for(col = 0; col < SIZE; col++) { comp_score += board[row][col] == "@"; user_score += board[row][col] == "O"; } printf("The final score is:\n"); printf("Computer %d\n User %d\n\n", comp_score, user_score); fflush(stdin); /* Flush the input buffer */ printf("Do you want to play again (y/n): "); scanf("%c", &again); /* Get y or n */ }while(tolower(again) == "y"); /* Go again on y */ printf("\nGoodbye\n");
} /***********************************************
* Function to display the board in it"s * * current state with row numbers and column * * letters to identify squares. * * Parameter is the board array. * ***********************************************/
void display(char board[][SIZE]) {
int row = 0; /* Row index */ int col = 0; /* Column index */ char col_label = "a"; /* Column label */ printf("\n "); /* Start top line */ for(col = 0 ; col<SIZE ;col++) printf(" %c", col_label+col); /* Display the top line */ printf("\n"); /* End the top line */ /* Display the intermediate rows */ for(row = 0; row < SIZE; row++) { printf(" +"); for(col = 0; col<SIZE; col++) printf("---+"); printf("\n%2d|",row + 1); for(col = 0; col<SIZE; col++) printf(" %c |", board[row][col]); /* Display counters in row */ printf("\n"); } printf(" +"); /* Start the bottom line */ for(col = 0 ; col<SIZE ;col++) printf("---+"); /* Display the bottom line */ printf("\n"); /* End the bottom line */
} /*********************************************** /* Calculates which squares are valid moves *
* for player. Valid moves are recorded in the * * moves array - 1 indicates a valid move, * * 0 indicates an invalid move. * * First parameter is the board array * * Second parameter is the moves array * * Third parameter identifies the player * * to make the move. * * Returns valid move count. * ***********************************************/
int valid_moves(char board[][SIZE], int moves[][SIZE], char player) {
int rowdelta = 0; /* Row increment around a square */ int coldelta = 0; /* Column increment around a square */ int row = 0; /* Row index */ int col = 0; /* Column index */ int x = 0; /* Row index when searching */ int y = 0; /* Column index when searching */ int no_of_moves = 0; /* Number of valid moves */ /* Set the opponent */ char opponent = (player == "O")? "@" : "O"; /* Initialize moves array to zero */ for(row = 0; row < SIZE; row++) for(col = 0; col < SIZE; col++) moves[row][col] = 0; /* Find squares for valid moves. */ /* A valid move must be on a blank square and must enclose */ /* at least one opponent square between two player squares */ for(row = 0; row < SIZE; row++) for(col = 0; col < SIZE; col++) { if(board[row][col] != " ") /* Is it a blank square? */ continue; /* No - so on to the next */ /* Check all the squares around the blank square */ /* for the opponents counter */ for(rowdelta = -1; rowdelta <= 1; rowdelta++) for(coldelta = -1; coldelta <= 1; coldelta++) { /* Don"t check outside the array, or the current square */ if(row + rowdelta < 0 || row + rowdelta >= SIZE || col + coldelta < 0 || col + coldelta >= SIZE || (rowdelta==0 && coldelta==0)) continue; /* Now check the square */ if(board[row + rowdelta][col + coldelta] == opponent) { /* If we find the opponent, move in the delta direction */ /* over opponent counters searching for a player counter */ x = row + rowdelta; /* Move to */ y = col + coldelta; /* opponent square */ /* Look for a player square in the delta direction */ for(;;) { x += rowdelta; /* Go to next square */ y += coldelta; /* in delta direction*/ /* If we move outside the array, give up */ if(x < 0 || x >= SIZE || y < 0 || y >= SIZE) break; /* If we find a blank square, give up */ if(board[x][y] == " ") break; /* If the square has a player counter */ /* then we have a valid move */ if(board[x][y] == player) { moves[row][col] = 1; /* Mark as valid */ no_of_moves++; /* Increase valid moves count */ break; /* Go check another square */ } } } } } return no_of_moves;
} /************
* Finds the best move for the computer. This is the move for * * which the opponent"s best possible move score is a minimum. * * First parameter is the board array. * * Second parameter is the moves array containing valid moves. * * Third parameter identifies the computer. * ************/
void computer_move(char board[][SIZE], int moves[][SIZE], char player) {
int row = 0; /* Row index */ int col = 0; /* Column index */ int best_row = 0; /* Best row index */ int best_col = 0; /* Best column index */ int i = 0; /* Loop index */ int j = 0; /* Loop index */ int new_score = 0; /* Score for current move */ int score = 100; /* Minimum opponent score */ char temp_board[SIZE][SIZE]; /* Local copy of board */ int temp_moves[SIZE][SIZE]; /* Local valid moves array */ char opponent = (player == "O")? "@" : "O"; /* Identify opponent */ /* Go through all valid moves */ for(row = 0; row < SIZE; row++) for(col = 0; col < SIZE; col++) { if(moves[row][col] == 0) continue; /* First make copies of the board and moves arrays */ for(i = 0; i < SIZE; i++) for(j = 0; j < SIZE; j++) temp_board[i][j] = board[i][j]; /* Now make this move on the temporary board */ make_move(temp_board, row, col, player); /* find valid moves for the opponent after this move */ valid_moves(temp_board, temp_moves, opponent); /* Now find the score for the opponents best move */ new_score = best_move(temp_board, temp_moves, opponent); if(new_score<score) /* Is it worse? */ { /* Yes, so save this move */ score = new_score; /* Record new lowest opponent score */ best_row = row; /* Record best move row */ best_col = col; /* and column */ } } /* Make the best move */ make_move(board, best_row, best_col, player);
} /************
* Calculates the score for the current board position for the * * player. player counters score +1, opponent counters score -1 * * First parameter is the board array * * Second parameter identifies the player * * Return value is the score. * ************/
int get_score(char board[][SIZE], char player) {
int score = 0; /* Score for current position */ int row = 0; /* Row index */ int col = 0; /* Column index */ char opponent = player == "O" ? "@" : "O"; /* Identify opponent */ /* Check all board squares */ for(row = 0; row < SIZE; row++) for(col = 0; col < SIZE; col++) { score -= board[row][col] == opponent; /* Decrement for opponent */ score += board[row][col] == player; /* Increment for player */ } return score;
} /************
* Calculates the score for the best move out of the valid moves * * for player in the current position. * * First parameter is the board array * * Second parameter is the moves array defining valid moves. * * Third parameter identifies the player * * The score for the best move is returned * ************/
int best_move(char board[][SIZE], int moves[][SIZE], char player) {
int row = 0; /* Row index */ int col = 0; /* Column index */ int i = 0; /* Loop index */ int j = 0; /* Loop index */ char opponent = player=="O"?"@":"O"; /* Identify opponent */ char new_board[SIZE][SIZE] = { 0 }; /* Local copy of board */ int score = 0; /* Best score */ int new_score = 0; /* Score for current move */ /* Check all valid moves to find the best */ for(row = 0 ; row<SIZE ; row++) for(col = 0 ; col<SIZE ; col++) { if(!moves[row][col]) /* Not a valid move? */ continue; /* Go to the next */ /* Copy the board */ for(i = 0 ; i<SIZE ; i++) for(j = 0 ; j<SIZE ; j++) new_board[i][j] = board[i][j]; /* Make move on the board copy */ make_move(new_board, row, col, player); /* Get score for move */ new_score = get_score(new_board, player); if(score<new_score) /* Is it better? */ score = new_score; /* Yes, save it as best score */ } return score; /* Return best score */
} /*************
* Makes a move. This places the counter on a square,and reverses * * all the opponent"s counters affected by the move. * * First parameter is the board array. * * Second and third parameters are the row and column indices. * * Fourth parameter identifies the player. * *************/
void make_move(char board[][SIZE], int row, int col, char player) {
int rowdelta = 0; /* Row increment */ int coldelta = 0; /* Column increment */ int x = 0; /* Row index for searching */ int y = 0; /* Column index for searching */ char opponent = (player == "O")? "@" : "O"; /* Identify opponent */ board[row][col] = player; /* Place the player counter */ /* Check all the squares around this square */ /* for the opponents counter */ for(rowdelta = -1; rowdelta <= 1; rowdelta++) for(coldelta = -1; coldelta <= 1; coldelta++) { /* Don"t check off the board, or the current square */ if(row + rowdelta < 0 || row + rowdelta >= SIZE || col + coldelta < 0 || col + coldelta >= SIZE || (rowdelta==0 && coldelta== 0)) continue; /* Now check the square */ if(board[row + rowdelta][col + coldelta] == opponent) { /* If we find the opponent, search in the same direction */ /* for a player counter */ x = row + rowdelta; /* Move to opponent */ y = col + coldelta; /* square */ for(;;) { x += rowdelta; /* Move to the */ y += coldelta; /* next square */ /* If we are off the board give up */ if(x < 0 || x >= SIZE || y < 0 || y >= SIZE) break; /* If the square is blank give up */ if(board[x][y] == " ") break; /* If we find the player counter, go backwards from here */ /* changing all the opponents counters to player */ if(board[x][y] == player) { while(board[x-=rowdelta][y-=coldelta]==opponent) /* Opponent? */ board[x][y] = player; /* Yes, change it */ break; /* We are done */ } } } }
}
</source>
Storing and displaying proverbs in order of length
<source lang="cpp"> /* Beginning C, Third Edition
By Ivor Horton ISBN: 1-59059-253-0 Published: Apr 2004 Publisher: apress
- /
/********************
* This program will read any number of proverbs of any length. * * The input buffer has a default size that is increased automatically * * if it is not large enough. The current contents of the old buffer * * are copied to the new and the old buffer is released before input * * continues. * * The same applies to the number of proverbs. If the initial capacity * * for pointers to proverbs is exceeded, a larger space is allocated * * and the existing pointers are copied to the new memory before releasing * * the old memory. * * You could add printf() statements to record when new memory is allocated* * Values for BUFFER_LEN, BUFFER_LEN_INCR, and CAPACITY_INCR are set low * * so as to cause frequent reallocation of memory for you to track. * * In a practical program they would be set much higher to avoid * * frequent allocation and release of memory. *
- /
- include <stdio.h>
- include <stdlib.h>
- include <string.h>
- define BUFFER_LEN 5 /* Initial length of input buffer */
- define BUFFER_LEN_INCR 2 /* Increment to buffer length */
- define CAPACITY_INCR 2 /* Increment to capacity for proverbs */
void main() {
char **pProverbs = NULL; /* Pointer to string pointer */ char **temp = NULL; /* Temporary pointer to string pointer */ int capacity = 0; /* Number of proverbs that can be stored */ int count = 0; /* Number of proverbs read */ char *pbuffer = NULL; /* Pointer to buffer */ char *pstart = NULL; /* Pointer to buffer start */ char *pstr = NULL; /* Pointer to a string */ int buffer_length = BUFFER_LEN; /* Buffer length */ int i = 0; /* Loop counter */ int j = 0; /* Loop counter */ pbuffer = (char*)malloc(BUFFER_LEN); /* Initial buffer size */ pstart = pbuffer; /* Store start of buffer */ for(;;) { if(count==capacity) { capacity += CAPACITY_INCR; temp = (char**)malloc(capacity*sizeof(char*)); if(temp == NULL) /* If memory was not allocated */ { /* Output a message and end */ printf("Memory allocation failed. Terminating program."); exit(1); } if(pProverbs == NULL) /* Are there any proverbs? */ pProverbs = temp; /* No - so just copy address of new memory */ else /* Yes - so copy data from old to new */ { for(i = 0 ; i<count ; i++) *(temp+i) = *(pProverbs+i); free(pProverbs); /* Free the old memory */ pProverbs = temp; /* Copy address of new */ } temp = NULL; /* Reset pointer */ } printf("Enter a proverb or press Enter to end:\n"); /* Read a proverb */ while((*pbuffer++ = getchar()) != "\n") { if(pbuffer-pstart == buffer_length) /* Check for buffer full */ { buffer_length += BUFFER_LEN_INCR; /* Increase buffer length */ pstr = (char*)malloc(buffer_length); /* Allocate new buffer */ /* Copy old buffer contents to new */ for(i = 0; i<pbuffer-pstart ; i++) *(pstr+i) = *(pstart+i); pbuffer = pstr+(pbuffer-pstart); /* Address of next position in new */ free(pstart); /* Release old buffer memory */ pstart = pstr; /* Set to start of new buffer */ pstr = NULL; /* Reset pointer */ } } /* check for empty line indicating end of input */ if((pbuffer-pstart)<2) break; /* Check for string too long */ if((pbuffer - pstart) == BUFFER_LEN && *(pbuffer-1)!= "\n") { printf("String too long ?maximum %d characters allowed.", BUFFER_LEN); pbuffer = pstart; continue; } *(pbuffer-1) = "\0"; /* Add string terminator */ pbuffer = pstart; *(pProverbs+count) = (char*)malloc(strlen(pstart)+1); strcpy(*(pProverbs+count++),pstart); } /* Order the proverbs from shortest to longest */ for(i = 0 ; i<count-1 ; i++) for(j = i+1 ; j<count ; j++) if(strlen(*(pProverbs+i))>strlen(*(pProverbs+j))) { pstr = *(pProverbs+i); *(pProverbs+i) = *(pProverbs+j); *(pProverbs+j) = pstr; } /* Output all the strings */ printf("\nIn ascending length order, the proverbs you entered are:\n"); for (i = 0 ; i<count ; i++ ) { printf("\n%s", *(pProverbs + i)); free(*(pProverbs + i)); /* Release the memory for the proverb */ *(pProverbs + i) = NULL; /* Set pointer back to NULL for safety */ } free(pProverbs); /* Release memory for the pointers */ free(pstart); /* Release memory for the buffer */
}
</source>
String length and string compare
<source lang="cpp">
- include <string.h>
- include <stdio.h>
int main(void) {
char str1[80], str2[80]; int i; printf("Enter the first string: "); gets(str1); printf("Enter the second string: "); gets(str2); /* see how long the strings are */ printf("%s is %d chars long\n", str1, strlen(str1)); printf("%s is %d chars long\n", str2, strlen(str2)); /* compare the strings */ i = strcmp(str1, str2); if(!i) printf("The strings are equal.\n"); else if(i<0) printf("%s is less than %s\n", str1, str2); else printf("%s is greater than %s\n", str1, str2); /* concatenate str2 to end of str1 if there is enough room */ if(strlen(str1) + strlen(str2) < 80) { strcat(str1, str2); printf("%s\n", str1); } /* copy str2 to str1 */ strcpy(str1, str2); printf("%s %s\n", str1, str2); return 0;
}
</source>
Use gets to get the whole string
<source lang="cpp">
- include <stdio.h>
int main(void) {
char str[80]; printf("Enter a string (less than 80 chars): "); gets(str); printf(str); /* output the string */ return 0;
}
</source>