search
HomeBackend DevelopmentC#.Net TutorialWhat does string assignment mean?

Strings are mainly used for programming. Strings are similar to character arrays in storage, so a single element of each bit can be extracted. For example, s="abcdefghij", then s[1]="a", s[9]="j", and the zero position of the string is exactly its length, such as s[0]=10 (※Ansistring does not have the above function.) This can provide us with a lot of convenience, such as high-precision operations Each bit can be converted into a number and stored in an array.

What does string assignment mean?

#But string assignment has certain requirements. For example, C language operators cannot operate strings at all. In C language, strings are treated as arrays. Therefore, strings are subject to the same restrictions as arrays. In particular, they cannot be copied and compared using C language operators.

String assignment method

In C language, there are two forms of string expression: one is in the form of a character array, such as char str[20] ="I love china"; The other is in the form of a character pointer, such as char *str="I love china". Strings can be assigned to character pointer variables, or strings can be stored in character arrays. Because the C language does not directly provide syntactic sugar support for strings. Moreover, many methods of the C standard library process strings based on the null character termination, which must be remembered.

char *p,a='5';
p=&a;                     //显然是正确的,
p="abcd";              //但为什么也可以这样赋值??

In the above program, double quotes do three things: apply for space (in the constant area) and store the string; add '/0' at the end of the string; return address. Here, the returned address is assigned to p.

But why does the char *p = “hello”; expression work, but changing p into an array and then assigning a value does not work. This is because when the string constant "hello" appears in an expression, the value used by the "hello" expression is the address where these characters are stored (in the constant area), not the characters themselves.

So, you can assign a string to a pointer p that points to a character, but you cannot assign a string to a character array.

char a[10] = “hello”; This is also possible. This situation is supported by c language initialization. If it is written as char a[10] then a = "hello" this is wrong. It is also an array of a, char a[10] = “hello”; this is the initialization of the array, and it is the same as a[0] = ‘h’ a[1] = ‘e’….

But changing to char a [10], then a = "hello" will not work. The value assigned to "hello" is an address, and although a also has an address, this is different from a pointer. A pointer The value of is an address, and although the value of the array is also an address, it is a constant, so a constant cannot be assigned a value. [3]

Let’s test it:

#include <stdio.h> int main(){       char *p = "hello";        printf("%s",p);       
        char a[10];        a = "hello";      
        return 0;}error C2440: &#39;=&#39; : cannot convert from &#39;char [6]&#39; to &#39;char [10]&#39;        There is no context in which this conversion is possible

When you see such an error message, try changing char a[10] to char a[6]

error C2106: ‘=’ : left operand must be l-value

The left side of the operator should be an "lvalue". The so-called "lvalue" refers to the amount that occupies memory space in the program and can be modified, such as various variables.

When using a pointer, the pointer can be incremented, but the array name cannot be incremented. The compiler allocates space to the array, and the address of the array a represents a constant. Letting the constant increment itself is definitely not possible. .

At the same time, when the pointer is incremented, the compiler will automatically identify the type. For example, if the pointer points to int type, if you want to get the next address, just p the pointer. Don't bother with p 4. .

It should be noted that when using void pointers, pointer arithmetic cannot be used, because the void compiler cannot recognize the length of the type (that is, the volume of the object pointed to by the pointer). p This is illegal. That is to say, mathematical operations cannot be performed, and the * value operation cannot be used. If you want to use it, you must convert it to other types.

The above is the detailed content of What does string assignment mean?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# var keyword best practicesC# var keyword best practicesJul 21, 2025 am 03:02 AM

When using var, it should be determined based on whether the type is clear and whether the readability is affected. 1. When the type is clear on the right side of the assignment, such as varlist=newList(); can improve the code simplicity; 2. When the type is fuzzy or returns to object or interface type, var should be avoided, such as IEnumerableresult=SomeMethod(); to improve readability; 3. Use var reasonably in anonymous types and LINQ queries, such as receiving anonymous objects, but subsequent processing is recommended to encapsulate it as a specific type; 4. In team projects, coding style should be unified, and var should be used reasonably through .editorconfig or code review to avoid abuse and affect maintenance.

How to compare two strings in C#?How to compare two strings in C#?Jul 21, 2025 am 02:49 AM

Comparing strings in C# should be based on the scene selection method. The == operator is case-sensitive by default and compared based on the current culture, but is not suitable for complex scenarios. 1. Using the == operator is suitable for quick comparison, but may not meet the expected results due to culture or case; 2. Using String.Equals() and passing in StringComparison enumeration can achieve more precise control, such as Ordinal, OrdinalIgnoreCase, InvariantCulture, etc.; 3. Pay attention to handling null or empty strings when comparing. It is recommended to use the string.Equals() static method or use string.IsNullOrEmpt first.

How to format a DateTime to a custom string in C#?How to format a DateTime to a custom string in C#?Jul 21, 2025 am 02:46 AM

The most common method of formatting DateTime objects into custom strings in C# is to use the ToString() method and pass in the format string, which includes: 1. Use standard format strings such as "d", "D", "t", and "T" to quickly implement common date and time formats; 2. Accurately control the output format through custom format strings such as "yyyy-MM-dd", "dd/MM/yyyyHH:mm"; 3. Use CultureInfo to handle format differences in different cultural environments to adapt to multilingual users.

C# LINQ query syntax vs method syntaxC# LINQ query syntax vs method syntaxJul 21, 2025 am 02:38 AM

The query syntax or method syntax of LINQ should be selected according to the scene. ① Query syntax is suitable for SQL-like expressions, such as multi-step filtering, projection, sorting, multi-table joining, grouping statistics, etc., with clear and intuitive structure; ② The method syntax is more flexible, supports chain calls and dynamic query conditions construction, and is suitable for aggregation functions, asynchronous operations and scenarios where splicing logic is required; ③ Some operations such as Take, Skip, Any, etc. can only use method syntax. The two functions are the same, and the choice mainly depends on personal habits and specific needs. Reasonable mixing of the two can improve the readability and maintenance of the code.

How to create a custom exception in C#?How to create a custom exception in C#?Jul 20, 2025 am 01:43 AM

The core of creating custom exceptions in C# is to inherit the Exception class or its subclasses to improve the accuracy of error messages and code maintainability. 1. Custom exceptions can more specifically express error scenarios in business logic, such as InvalidLoginException clearly indicates login problems; 2. Its benefits include improving code readability, better distinguishing error types, and conveniently handling specific exceptions in a unified manner; 3. When creating, you need to inherit the Exception class and implement at least three constructors without parameters, with message parameters, with message and internal exceptions; 4. If serialization support is required, you can implement the ISerializable interface; 5. Throw it when a specific error condition is detected, such as using thrown when verification fails.

What are lambda expressions in C#?What are lambda expressions in C#?Jul 20, 2025 am 01:20 AM

Lambda expressions are used in C# to write inline, anonymous functions that can be used anywhere you need to delegate. They are simple and flexible, especially suitable for LINQ or asynchronous code. Lambda expressions use the => operator, on the left are input parameters, on the right are expressions or statement blocks; for example, x=>xx represents a lambda that accepts x and returns its squared. If there are multiple parameters, it needs to be wrapped in brackets, such as (intx,inty)=>x y, the type can be omitted and inferred by the compiler. Common uses include LINQ query, event processing, asynchronous programming, etc., such as numbers.Where(n=>n%2==0) filtering even numbers. Unlike the conventional method, lambda

C# thread vs task: which is better?C# thread vs task: which is better?Jul 20, 2025 am 01:10 AM

In C#, Thread is suitable for underlying scenarios that require fine control of threads, such as long-running services or exclusive resource tasks; Task is recommended for modern application development because it is based on thread pools, supports asynchronous waiting, has advanced functions and is more efficient. 1.Thread directly operates operating system threads, suitable for background services and tasks that clearly require exclusive threads, but create and destroy costs, consume high resources, and lack a built-in asynchronous mechanism. 2.Task automatically utilizes thread pools to save resources, supports cancellation, exception handling, await and other features, and is commonly found in UI optimization, parallel computing, I/O operation and other scenarios. 3. The key difference between the two is: Thread is an underlying implementation, with high resource consumption and fine control granularity, while Task abstraction

How to parse a string to an enum in C#?How to parse a string to an enum in C#?Jul 20, 2025 am 12:59 AM

When parsing a string into an enum type in C#, you should preferentially use the Enum.TryParse method to avoid exceptions, and combine Enum.IsDefined to ensure the value is legal. 1. Use Enum.TryParse to safely parse strings, return a Boolean value to indicate success or not, and support ignoring case; 2. Can handle entire numeric strings such as "1", and still ensure that the value actually exists in the enum definition; 3. Enum.IsDefined must explicitly verify whether the parsing result is a valid member of the enum to prevent illegal values from being mistakenly considered valid. Mastering these key points ensures the robustness of the string-to-enum conversion.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),