Wins the offer of a string

I believe we strings used in life, today I want to tell you a little knowledge points to explain:

  1. String constants and character arrays
  •  String constants: char * arr, accounted for four bytes, can not make changes to read-only. After the plurality of string constants initialized to the same value, they point to the same memory space, it will be equal.
  • Array of characters: char arr [], with a few bytes allocated several bytes, '\ 0' one byte, can be changed, if a plurality of character array is initialized to the same value, the system will be assigned to each space, so it will not point to the same memory space. Alternative solution spaces

    2. Replace the string space

  • Problem Description: Make a function implemented, each of the replacement string is "20%" for example, enter "we are happy", the output "we% 20are% 20happy".  
  • Problem Analysis: From the formal point of view the subject is treated after a string of questions will be longer, the beginning I would like to come back space, the number behind the first move, but so too complex, and a waste of space this is a replacement of the former backward thinking, it would make some elements are moved twice. So we put it another thought, it is to replace the data from before, so after all the numbers will only move once, let's take a specific look at a map by

 

# include <stdio.h>
# include <string.h>
void replace(char *a,int len)
{
	int p=0;
	int q=0;
	int count=0;
	for(int i=0;a[i]!='\0';i++)
	{
		if(a[i]==' ')
		{
			count++;
		}
		p++;
	}
	q=p+2*count;
	while(p!=q)
	{
		if(a[p]==' ')
		{
			p--;
			a[q--]='0';
			a[q--]='2';
			a[q--]='%';
			
		}
		else
		{
			a[q]=a[p];
			p--;
			q--;
		}
	}
}
void show(char *a,int len)
{
	for(int i=0;a[i]!='\0';i++)
	{
		printf("%c ",a[i]);
	}
}
int main()
{
	char a[100]="we are happy.";
	show(a,100);
	printf("\n");
	replace(a,100);
	show(a,100);
}

operation result:

Come on! ! !

Published 54 original articles · won praise 8 · views 5324

Guess you like

Origin blog.csdn.net/qq_43411555/article/details/90274436