Mudanças entre as edições de "AULA Exercicios Strings - Programação 1 - Engenharia"
Linha 1: | Linha 1: | ||
+ | =Objetivos= | ||
+ | |||
+ | Após esta aula o aluno deverá ser capaz de utilizar as funções strlen(), strcpy, strcmp() e strcat() em pequenos programas C. | ||
+ | |||
=Funções da Biblioteca C para Operação com Strings= | =Funções da Biblioteca C para Operação com Strings= | ||
Edição das 13h23min de 21 de julho de 2021
Objetivos
Após esta aula o aluno deverá ser capaz de utilizar as funções strlen(), strcpy, strcmp() e strcat() em pequenos programas C.
Funções da Biblioteca C para Operação com Strings
O C proporciona um rico conjunto de funções para manipulação de strings. Para uso destas funções deve-se incluir o arquivo cabeçalho <string.h>
Computação do tamanho da String - Função strlen()
#include <stdio.h>
#include <string.h>
int main()
{
char x[100] = "IFSC-";
char y[100] = "Telecom SJ";
int tam;
tam = strlen(x);
printf("x - > %s com tamanho %d\n", x, tam);
printf("y - > %s com tamanho %ld\n", y, strlen(y));
return 0;
}
Comparação de strings- strcmp()
Já existe a função strcmp() da biblioteca que permite comparar strings. Esta função retorna:
- 0 se as strings são iguais
- menor que zero se o primeiro caracter que não é igual, é menor na primeira string
- maior que que zero se o primeiro caracter que não é igual, é maior na primeira string;
Exemplo: considere as duas strings "ifsc' e iFsc". Diferem na posição 1 (não esquecer que começa em zero). O retorno da função será 'f' - 'F' que é (olhar na tabela ascii) 112-70 = 32
#include <stdio.h>
#include <string.h>
int main()
{
char x[100] = "IFSC-";
char y[100] = "Telecom SJ";
int ret;
ret = strcmp(x,y);
if(ret==0)
printf("strings iguais\n");
return 0;
}
Concatenação de Strings strcat()
Copia de Strings strcpy()
Exercícios sobre strings
1.Implementar uma função para adicionar (append) n caracteres iniciais de uma string2 para o final de uma string1. Retornar 0 se sucesso ou -1 se detectado algum problema.
int str_ncat(char string1[], char string2[], int n)
Solução - Exercicio 01 |
---|
#include <stdio.h>
int str_len(char x[])
{
int i=0;
printf ("Endereço de x é %p\n", x);
while (x[i]!=0)
i++;
return i;
}
int str_ncat(char string1[], char string2[], int n)
{
int i,j;
if (n<=0)
return -1;
i = str_len(string1);
for (j=0;j<n && string2[j]!=0;j++) {
string1[i] = string2[j];
i++;
}
string1[i] =0;
return 0;
}
int main()
{
char x[100]="IFSC-";
char y[100]="Telecom SJ";
str_ncat(x,y,30);
printf("x - > %s\n", x);
}
|
2.Implementar uma função para adicionar (append) a uma subcadeia da string2 para uma string1. A substring é iniciada no índice determinado por n.
int str_nicat(char string1[], char string2[], int n)
Solução - Exercicio 02 |
---|
//Autor: Victor Cesconetto De Pieri
#include <stdio.h>
int str_len(char x[]) {
int i = 0;
while (x[i] != 0)
i++;
return i;
}
int str_ncat(char string1[], char string2[], int n) {
int i, j;
if (n >= str_len(string2) || n < 0) {
printf("Numero invalido ou excede o tamanho da string 2\n");
return -1;
}
i = str_len(string1);
for (j = n; string2[j] != 0; j++) {
string1[i] = string2[j];
i++;
}
if (string2[j] != 0)
string1[i] = 0;
return 0;
}
main() {
char x[100] = "IFSC-";
char y[100] = "Telecom SJ";
str_ncat(x, y, 0); // 0 para a substring ser iniciada pelo começo da string 2, se fosse "1" ficaria "IFSC-elecom SJ", "2" - "IFSC-lecom SJ" na saida e assim por diante...
printf("x - > %s\n", x);
}
|
3.Implementar uma função para comparar até n primeiros caracteres de duas cadeias passadas como parâmetro. Retornar 0 se iguais, -1 se diferentes.
int str_ncmp(char string1[], char string2[], int n)
Solução - Exercicio 03 |
---|
//Autor:Victor Cesconetto De Pieri
#include <stdio.h>
int str_len(char x[])
{
int i=0;
//printf ("Endereço de x é %p\n", x);
while (x[i]!=0)
i++;
return i;
}
int str_ncmp(char string1[], char string2[], int n)
{
int i,j;
if(n>str_len(string1) || n>str_len(string2) || n<0){
printf("Valor de tamanho excede string 1 ou string 2 ou é invalido\n");
return -1;
}
for (j=0;j<n;j++) {
if(string1[j]!=string2[j]){
return -1;
}
}
return 0;
}
main()
{
int i;
char x[100]="IFSC-";
char y[100]="IFSC-SJ";
i = str_ncmp(x,y,3);//compara ate o valor valido, se a string for igual ate o valor retorna 0, caso contrario retorna -1.
printf("i - > %d\n", i);
}
|
4.Implementar uma função para comparar uma substring da string2 com os n2 primeiros caracteres de string1. A substring é determinada pelo índice n1 com tamanho dado por n2. Retornar 0 se sucesso e -1 se problemas.
int str_nicmp(char string1[],char string2[], int n1, int n2)
Solução - Exercicio 04 |
---|
//Autor: Victor Cesconetto De Pieri
#include <stdio.h>
int str_len(char x[])
{
int i=0;
//printf ("Endereço de x é %p\n", x);
while (x[i]!=0)
i++;
return i;
}
int str_ncmp(char string1[], char string2[], int n1, int n2)
{
int i=0,j;
char straux[n2-n1];
if(n1 > str_len(string2) || n2 > str_len(string2) || n1<0 || n2<0){
printf("Valor de tamanho excede tamanho da string 2 ou da string1 ou é invalido\n");
return -1;
}
for (j=n1;j<n2;j++) {
straux[i] = string2[j];//passando a substring para uma string aux
i++;
}
for(j=0;j<n2;j++){
if(straux[j]!=string1[j]){
return -1; //verificando se a string aux é igual ao n2 caracteres da string1
}
}
return 0;
}
main()
{
int i;
char x[100]="IFSC-";
char y[100]="IFSC-SJ";
i = str_ncmp(x,y,0,2);//compara ate o valor valido, se a string for igual ate o valor retorna 0, caso contrario retorna -1.
printf("i - > %d\n", i);
}
|
5.Implementar uma versão não sensitiva a case da função str_cmp.
Solução - Exercicio 05 |
---|
//Autor:Victor Cesconetto De Pieri
#include <stdio.h>
int str_len(char x[]) {
int i = 0;
//printf ("Endereço de x é %p\n", x);
while (x[i] != 0)
i++;
return i;
}
//funcao para deixar todas as casas minusculas, assim nao terá case sensitive na comparacao
int to_lower(int c) {
if (c <= 'Z' && c >= 'A') return c + 32;
return c;
}
int str_cmp(char string1[], char string2[]) {
int i, j;
for (j = 0; string1[j] != 0 && string2[j] != 0; j++) {
if (to_lower(string1[j]) != to_lower(string2[j])) {
return -1;
}
}
return 0;
}
main() {
int i;
char x[100] = "ifsc-sj";
char y[100] = "IFSC-SJ";
i = str_cmp(x, y); //compara ate o valor valido, se a string for igual ate o valor retorna 0, caso contrario retorna -1.
printf("i - > %d\n", i);
}
|